Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute specified task at the specified time

Tags:

c#

I am new to C# but java has method to execute specified task at the specified time so using c# how it doing

Timer t=new Timer();
TimerTask task1 =new TimerTask()           

t.schedule(task1, 3000);
like image 212
mssb Avatar asked Dec 07 '22 13:12

mssb


2 Answers

You can get a complete tutorial of how timer works in C# here : http://www.dotnetperls.com/timer

In Short:

using System;
using System.Collections.Generic;
using System.Timers;

public static class TimerExample // In App_Code folder
{
    static Timer _timer; // From System.Timers
    static List<DateTime> _l; // Stores timer results
    public static List<DateTime> DateList // Gets the results
    {
        get
        {
            if (_l == null) // Lazily initialize the timer
            {
                Start(); // Start the timer
            }
            return _l; // Return the list of dates
        }
    }
    static void Start()
    {
        _l = new List<DateTime>(); // Allocate the list
        _timer = new Timer(3000); // Set up the timer for 3 seconds
        //
        // Type "_timer.Elapsed += " and press tab twice.
        //
        _timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);
        _timer.Enabled = true; // Enable it
    }
    static void _timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        _l.Add(DateTime.Now); // Add date on each timer event
    }
}
like image 82
basarat Avatar answered Dec 24 '22 16:12

basarat


Using Anonymous Methods and Object Initializer:

var timer = new Timer { Interval = 5000 };
timer.Tick += (sender, e) =>
    {
        MessageBox.Show(@"Hello world!");
    };
like image 43
Ria Avatar answered Dec 24 '22 15:12

Ria