d

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore.

15 St Margarets, NY 10033
(+381) 11 123 4567
ouroffice@aware.com

 

KMF

Trigger C# Functions on Specific Intervals

Introduction

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:

.NET Tasks construct

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:

Changing code in the Main method

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

Program output

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:

Timer class utilization

And here is the output of program execution:

Program execution output

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.

Credit: Source link

Previous Next
Close
Test Caption
Test Description goes like this