Josh
Josh

Reputation: 141

Better Timer Management?

I'm working on an IRC bot in VB.net 2012. I know I know, but it's not a botnet, lol I wanted to ask your advise on how to manage to many timers. Right now I have a timer that rewards points at a user specified interval, a timer that autosaves those points at a user specified interval. I also have one that displays advertisements, and broadcast a collection of responses at specified intervals.

I feel like it's getting out of hand and would love to know if there is a way I could do all of these thing with a single or at least less timers.

Please keep in mind I learn as I go and don't always understand all the terminology, but I am a quick learner if you have the patience to explain. :)

Thank you.

Upvotes: 1

Views: 108

Answers (1)

Cody Gray
Cody Gray

Reputation: 244981

Yes, of course you can do them with a single timer. In fact, that is what you should do—timers are a limited resource, and there's hardly ever a reason for a single application to use more than one of them.

What you do is create a single timer that ticks at the most frequent interval required by all of your logic. Then, inside of that timer's Tick event handler, you set/check flags that indicate how much time has elapsed. Depending on which interval has expired, you perform the appropriate action and update the state of the flags. By "flags", I mean module-level variables that keep track of the various intervals you want to track—the ones you're tracking now with different timers.

It is roughly the same way that you keep track of time using a clock. You don't use separate clocks for every task you want to time, you use a single clock that ticks every second. You operate off of displacements from this tick—60 of these ticks is 1 minute, 3600 of these ticks is 1 hour, etc.

However, I strongly recommend figuring out a way to do as many of these things as possible in response to events, rather than at regular intervals tracked by a timer. You could, for example, reward points in response to specific user actions. This type of polling is very resource-intensive and rarely the best solution.

Upvotes: 2

Related Questions