zoukankan      html  css  js  c++  java
  • C#定时任务(Timer)

    新建Timer类

    using BaseAsset.Data.Infrastructure;
    using BaseAsset.Data.Repositories;
    using BaseAsset.Entities;
    using BaseAsset.Services;
    using BaseAsset.Services.Abstract;
    using System;
    using System.Threading;
    using System.Timers;
    
    namespace BaseAsset.Api.Timer
    {
        public class CostanalysisTimer 
        {
            private static int inTimer = 0;
            public  void SetTimer()
            {
                System.Timers.Timer aTimer = new System.Timers.Timer();
    
                aTimer.Elapsed += new ElapsedEventHandler(OnTimer);
                //aTimer.Interval = 60000;
                aTimer.Interval = 10800000;
                aTimer.Enabled = true;
            }
            public  void OnTimer(Object source, ElapsedEventArgs e)
            {
                try
                {
                    //防止重入问题
                    if (Interlocked.Exchange(ref inTimer, 1) == 0)
                    {
                        IFoodService _foodService = new FoodService(
                           new EntityBaseRepository<fd_purchase>(),
                           new EntityBaseRepository<fd_purchase_detail>(),
                           new EntityBaseRepository<fd_cost_analysis>(),
                           new EntityBaseRepository<fd_cost_analysis_detail>(), new UnitOfWork());//工作单元实例化(工作单元的接入,保证了数据上下文在一个操作单元中只有一个,它可以通过构造方法注入到其它类中,实现跨类进行方法的组合。)
                        _foodService.Addcostanalysis();
                        Interlocked.Exchange(ref inTimer, 0);
                    }
                }
                catch (Exception ex)
                {
                    Interlocked.Exchange(ref inTimer, 0);
                    throw (ex);
                }
    
            }
        }
    }
    Global.asax
    using BaseAsset.Api.Mappings;
    using BaseAsset.Api.Timer;
    using System.Web.Http;
    
    namespace BaseAsset.Api
    {
        public class WebApiApplication : System.Web.HttpApplication
        {
    
            protected void Application_Start()
            {
                CostanalysisTimer time = new CostanalysisTimer();
                time.SetTimer();
            }
           
        }
    }
     
  • 相关阅读:
    加一
    斐波那契数
    整数的各位积和之差
    移除元素
    删除排序数组中的重复项
    有效的括号
    爬楼梯
    最长公共前缀
    罗马数字转整数
    回文数
  • 原文地址:https://www.cnblogs.com/yyjspace/p/13224911.html
Copyright © 2011-2022 走看看