Click here to Skip to main content
15,905,144 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
I need to call a function periodically (with start time and an interval) in windows service application. Other than timer and windows task scheduler is there any better way? Pls suggest.Thanks.

What I have tried:

Is that possible using async task?
Posted
Updated 2-Nov-16 21:54pm
v2

Don't know if it fits your requirements. But it works to me.
C#
public void InitJob() 
{
    Action job = () => { Console.WriteLine($"Running {DateTime.Now}"); };
    Func<DateTime> computeNextStart = () => 
    {
        var now = DateTime.Now;
        return now.Date 
               + TimeSpan.FromHours(now.Hour) 
               + TimeSpan.FromMinutes(now.Minute + 1);
    };
    ThreadPool.QueueUserWorkItem(
        (state) => ExecuteJobTimedAsync(job, computeNextStart));
}

private static async void ExecuteJobTimedAsync(
    Action job,
    Func<DateTime> computeNextStart) 
{
    DateTime waitUntil = computeNextStart();
    TimeSpan wait = waitUntil - DateTime.Now;
    if (wait > TimeSpan.Zero) await Task.Delay(wait).ConfigureAwait(false);
    job();
    ThreadPool.QueueUserWorkItem(
        (state) => ExecuteJobTimedAsync(job, computeNextStart));
}

The example executes the job every full minute (see computeNextStart); while the job does not take longer than a minute.
 
Share this answer
 
The best way is to make use of threading to achieve such requirement.
-- create a thread
-- make sure that there is only one thread running at once
-- do the required operation
-- once the operation is finished sleep thread for the time mentioned in interval
-- repeat the process
-- also check whether there is any operation currently going on while stopping the service and accordingly wait till it finishes

Try this approach. In case you need more details implementing this approach, please let me know.

Hope, it helps :)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900