Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running task in loop

I have a function which can take 5-60 seconds to run, and I need to run it for every 10 seconds but it should be started only when the previously started function finished running, my code for now is

Action myAction = new Action(() =>
    {
        Debug.WriteLine("just testing");
        Thread.Sleep(15000);
    });
Task myTask = Task.Factory.StartNew(myAction, _cts.Token);
Timer myTimer = new Timer(state =>
    {
        if (myTask.IsCompleted)
        {
            myTask = Task.Factory.StartNew(myAction, _cts.Token);
        }
    }, null, 10000, 10000);

Everything is working fine but I wonder if there is a better solution for my problem? Or is there a possibility to not create a new task (Task.Factory.StartNew) but just using the one used by myTimer?

like image 214
cservice Avatar asked Jan 28 '26 16:01

cservice


2 Answers

You can use ContinueWith():

Task.Factory.StartNew(myAction, _cts.Token).ContinueWith(_ => myAction);

Look for it's overloads, it has many options to control on which cases to run the continuation.

like image 152
Pablo Montilla Avatar answered Jan 30 '26 06:01

Pablo Montilla


There is a great open source task scheduler called Quartz.net. You can find it at http://quartznet.sourceforge.net/

It supports the specific scenario you mentioned. It is a very robust solution with good extensibility.

like image 25
Chris Pritchard Avatar answered Jan 30 '26 04:01

Chris Pritchard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!