定时任务调度

在业务复杂的应用程序中,有时候会要求一个或者多个任务在一定的时间或者一定的时间间隔内计划进行,比如定时备份或同步数据库,定时发送电子邮件等,我们称之为计划任务。

定时任务调度实现方式:

1.Windows Service实现  2.WebApplication Timer定时任务  3.Windows定时任务调度

但是1,3可以实现在一定时间执行,2只能实现在一定时间间隔执行。

 

 

WebApplication方式:

(1)Thread方式(开启线程):

public class DateTimeClass
    {
        public void Parse()
        {
            while (true)
            {
                int time = int.Parse(DateTime.Now.ToString("ss"));
                Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "   ---  " + time);
                Thread.Sleep(3*1000);//每隔3秒执行一次任务
            }
        }

        public void ConsoleWirte()
        {
            ThreadStart threadStart = new ThreadStart(this.Parse);
            Thread thread = new Thread(threadStart);
            thread.Start();
        }
    }
class Program
    {
        static void Main(string[] args)
        {
            new DateTimeClass().ConsoleWirte();
        }    

    }

  (2)Timer方式:

using Timer = System.Timers.Timer;
class Program
    {
static void Main(string[] args)
        {
            Timer timer=new Timer();
            timer.Interval = 10000;
            timer.Enabled = true;
            timer.Elapsed += timer_Elapsed;
            Console.ReadKey();
        }
static void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            new DateTimeClass().ConsoleWirte();
        }
}

public class DateTimeClass
    {

        public void ConsoleWirte()
        {
            //ThreadStart threadStart = new ThreadStart(this.Parse);
            //Thread thread = new Thread(threadStart);
            //thread.Start();
            Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "   ---  " + 1);
        }
    }

  

posted @ 2015-11-13 14:17  《船长》  阅读(200)  评论(0编辑  收藏  举报