Trigger C# functions on specific intervals

Introduction

Sometimes we need to perform some action on 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 code base which 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 purpose 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.

The output of above code is shown as follows:

This starting code can be downloaded from this git repo (master branch).

Now, what we want is to call the printer.Print() method on specific interval e.g. after every two seconds.

Creating a 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 perform the action. After that it calls itself again.

Now, we can change our code in Main method with something like shown below:

Here is the output which shows that printer.Print() method is being called after specified interval:

Using Built-in Timer Object

Let’s see another example, which uses timer class to achieve the same functionality.

The following picture shows the code part which uses 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 purpose.

You can download the code from this git repo ( timerSample branch).

Let me know if you have some questions or comments.

My Recent Books