使用Windows服务定时去执行一个方法的三种方式

本文详细介绍了在C#服务中实现定时任务的三种方法:使用System.Timers.Timer定时器,使用Task结合CancellationTokenSource,以及一种未实践但被认为便捷的方法。每种方法都附带了具体的代码示例,帮助开发者理解如何在服务中定时执行特定任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

方式一:使用System.Timers.Timer定时器

public partial class Service1 : ServiceBase
    {
       
        private UnitOfWork unitOfWork;
        private System.Timers.Timer timer1;//初始化一个定时器        
        LogHelper lghelper = new LogHelper(typeof(Service1));
        public Service1()
        {
            InitializeComponent();
            unitOfWork = new UnitOfWork();
         this.timer1 = new System.Timers.Timer();
            this.timer1.Interval = 1000;//设置定时器启动的时间间隔
            this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Elapsed);//定时器定时执行的方法          
        }

        protected override void OnStart(string[] args)
        {
            this.timer1.Enabled = true;//服务启动时开启定时器
            lghelper.Info("服务启动");
        }

        protected override void OnStop()
        {
            this.timer1.Enabled = false;//服务停止时关闭定时器
            unitOfWork.Dispose();
            lghelper.Info("服务停止");
        }

        private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            this.timer1.Enabled = false;//在服务运行时关闭定时器,避免在服务还没有运行结束时达到定时器时间间隔又重头开始运行(比如该定时器设置为5分钟同步一次数据,当数据量很大时,5分钟同步不完,这时达到定时器时间间隔,又会重头开始同步,所以在服务开始运行时关闭定时器)
            lghelper.Info("服务开始运行");
            try
            {

                DoWork();
            }
            catch (Exception ex)
            {
                lghelper.Error(ex.ToString());
                lghelper.Info("服务运行失败");
                Thread.Sleep(5000);
            }

            this.timer1.Enabled = true;//服务运行结束,重新启动定时器
        }

       
    }

方式二:使用Task

  partial class Service2 : ServiceBase, IDisposable
    {
        LogHelper lghelper = new LogHelper(typeof(Service2));
        private CancellationTokenSource TokenSource = new CancellationTokenSource();
   protected UnitOfWork unitOfWork = new UnitOfWork();

        Task MainTask;
        public Service2()
        {
            InitializeComponent();
          

        }
        public void Dispose()
        {
            unitOfWork.Dispose();
        }

        protected override void OnStart(string[] args)
        {
            lghelper.Info("开启服务!");
            MainTask = Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    try
                    {
                      DoWork();

                    }
                    catch (Exception ex)
                    {
                        lghelper.Error(ex.ToString());

                        Thread.Sleep(60 * 60 * 1000);
                    }

                    Thread.Sleep(5 * 60 * 1000);
                }

            });

        }

        protected override void OnStop()
        {
            if (MainTask != null)
            {
                if (MainTask.Status == TaskStatus.Running) { }
                {
                    TokenSource.Cancel();
                    lghelper.Info("线程结束");
                }
            }
        }


     
    }

方式三:这个方法是看到博友的,还没有用过,不过觉得挺方便的

http://www.cnblogs.com/ldyblogs/p/timer.html

转载于:https://www.cnblogs.com/stubborn-donkey/p/7656284.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值