jadrijan
jadrijan

Reputation: 1446

C# execute a background thread every number of seconds (scheduled)

I just started learning C#, I am a Java programmer. In Java I am able to do the following:

    int corePoolSize = 1;
    long initialDelay = 0;//0 seconds
    long delay = 60;//60 seconds
    ScheduledThreadPoolExecutor stpe = new ScheduledThreadPoolExecutor(corePoolSize);
    stpe.scheduleWithFixedDelay(new MyDemoClass(), initialDelay, delay, TimeUnit.SECONDS);

which would execute the Runnable "MyDemoClass" in a background thread every 60 seconds.

How would I do this in C#? I have looked at its ThreadPool http://msdn.microsoft.com/en-us/library/3dasc8as(v=vs.80).aspx, but it seems to be not what I am looking for.

Thank you very much

Upvotes: 0

Views: 2691

Answers (2)

Jstone05
Jstone05

Reputation: 61

I think your looking for System.Threading.Timer
http://msdn.microsoft.com/en-us/library/system.threading.timer.aspx

"Use a TimerCallback delegate to specify the method you want the Timer to execute. The timer delegate is specified when the timer is constructed, and cannot be changed. The method does not execute on the thread that created the timer; it executes on a ThreadPool thread supplied by the system."

Upvotes: 1

Steve Townsend
Steve Townsend

Reputation: 54168

Use System.Timers.Timer with an Interval, wired to Elapsed event handler that performs your required periodic logic.

The Timer component is a server-based timer, which allows you to specify a recurring interval at which the Elapsed event is raised in your application. You can then handle this event to provide regular processing. For example, suppose you have a critical server that must be kept running 24 hours a day, 7 days a week. You could create a service that uses a Timer to periodically check the server and ensure that the system is up and running. If the system is not responding, the service could attempt to restart the server or notify an administrator.

You should not need thread pool to get this done.

Upvotes: 1

Related Questions