Trigger C# Functions on Specific Intervals
In this post, we will learn how to trigger some C# backend code on a specific interval to build a simple solution to achieve this functionality.
Join the DZone community and get the full member experience.
Join For FreeIntroduction
Sometimes we need to perform some action at specified intervals. For example, I was working on an application where I needed to simulate some server actions to be triggered automatically. In this post, we will learn how can we build a simple solution to achieve this functionality.
Setting the Scene
I will be using an existing codebase that utilized .NET Events. I wrote an article on this topic, which you can read if you need some background information about the code we’ll use today.
However, you can use your own existing code for such purposes as well.
Here is the application code for your reference:
Here we have very basic Printer and Reporter objects. Then we wired up an event handler which is raised whenever printer.Print() method is called.
This starting code can be downloaded from this git repo (master branch).
Requirement
Now, what we want is to call the printer.Print() method on specific interval e.g. after every two seconds.
Creating Custom SetInterval Method
An easy way to implement such functionality is to utilize .NET Tasks construct as shown in the following method implementation:
This method takes an Action and TimeSpan as its arguments and then performs the action. After that, it calls itself again.
Now, we can change our code in the Main method with something like shown below:
Here is the output which shows that printer.Print() method is being called after a specified interval:
Using Built-in Timer Object
Let’s see another example, which uses a timer class to achieve the same functionality. The following picture shows the code part which uses the timer class:
And here is the output of program execution:
Summary
In this post, we saw a very simple mechanism to execute some actions based on some interval. We saw two implementations for such a purpose.
You can download the code from this git repo ( timerSample branch).
Let me know if you have any questions or comments.
Published at DZone with permission of Jawad Hasan Shani. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments