Vivekh
Vivekh

Reputation: 4259

Running the windows service for every one minute

I have tried to run the service every 1 minute and i have succeeded in doing so but the problem is its starting every minute regardless of the completion of the program. I have written it like this

    private Timer _timer;
    private DateTime _lastRun = DateTime.Now.AddDays(-1);
    public SpotlessService()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        _timer = new Timer(1 * 60 * 1000); // every 1 hour
        _timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
        _timer.Start();


    }

    public void Start()
    {
        OnStart(new string[0]);
    }
    void timer_Elapsed(object sender, EventArgs e)
    {
        Util.LogError("Started at" + DateTime.Now + "");

        FileDownload objdwn = new FileDownload();
    }

I have hosted it as a service and FileDownload class constructor will download some files from server and will copy the data into the database which will take like 10-15 minutes. So what i need to do is i should stop the timer till these fifteen minutes and the service should start again and should wait for the next minute and do the same thing. is this possible or should i just increase the timer value to greater extent

Upvotes: 1

Views: 7749

Answers (2)

berkeleyjuan
berkeleyjuan

Reputation: 528

Stop() the timer at the beginning of the Elapse event and Start() the timer at the end. Also ensure your timer object does not get garbage collected.

private Timer _timer;
private DateTime _lastRun = DateTime.Now.AddDays(-1);
public SpotlessService()
{
    InitializeComponent();
}

protected override void OnStart(string[] args)
{
    _timer = new Timer(1 * 60 * 1000); // every 1 minute
    _timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
    _timer.Start();


}

public void Start()
{
    OnStart(new string[0]);
}
void timer_Elapsed(object sender, EventArgs e)
{
    _timer.Stop();

    Util.LogError("Started at" + DateTime.Now + "");

    FileDownload objdwn = new FileDownload();

    _timer.Start()
}

Upvotes: 2

razakj
razakj

Reputation: 1049

My suggestion is to use Task to perform download and call the main method again as soon as it is finished.

public void mainMethod() 
{
    Thread.Sleep(60000);
    doDownload();
}

public void doDownload() 
{
    Task.Factory.StartNew(() => {
        // Background download
    }).ContinueWith(task => mainMethod());
}

This will allow you to perform any additional operations in the main thread if needed while the download is in progress.

OR

You can just stop the timer and run again as soon as the download is done

void timer_Elapsed(object sender, EventArgs e)
{
    _timer.Stop();
    Util.LogError("Started at" + DateTime.Now + "");

    FileDownload objdwn = new FileDownload();
    _timer.Start();
}

Upvotes: 1

Related Questions