源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

c#定时器和global实现自动job示例

  • 时间:2020-05-10 20:57 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:c#定时器和global实现自动job示例
一、创建一个cs文件,定义Time 对象
[u]复制代码[/u] 代码如下:
 public class WebTimer_AutoRepayment {     static WebTimer_AutoRepayment()     {         _WebTimerTask = new WebTimer_AutoRepayment();     }     /// <summary>     /// 实例化     /// </summary>     /// <returns></returns>     public static WebTimer_AutoRepayment Instance()     {         return _WebTimerTask;     }     /// <summary>     /// 实际执行的方法     /// </summary>     private void ExecuteMain()     {         //定义你自己要执行的Job         ChinaPnrInterfaces.AutoSendRepaymentNotice();//定时发送短信提醒的方法     }     #region Timer 计时器定义     /// <summary>     /// 调用 callback 的时间间隔(以毫秒为单位)。指定 Timeout.Infinite 可以禁用定期终止。     /// </summary>     private static int Period = 1 * 60 * 60 * 1000;     /// <summary>     /// 调用 callback 之前延迟的时间量(以毫秒为单位)。指定 Timeout.Infinite 以防止计时器开始计时。指定零 (0) 以立即启动计时器。     /// </summary>     private static int dueTime = 3 * 1000;//三分钟后启动     /// <summary>     ///第几次执行     /// </summary>     private long Times = 0;     /// <summary>     /// 实例化一个对象     /// </summary>     private static readonly WebTimer_AutoRepayment _WebTimerTask = null;     private Timer WebTimerObj = null;     /// <summary>     /// 是否正在执行中     /// </summary>     private int _IsRunning;     /// <summary>     /// 开始     /// </summary>     public void Start()     {         if (WebTimerObj == null)         {             DateTime now = DateTime.Now;             int minutes = now.Minute;             if (minutes >= 55)             {                 dueTime = 0;//立即启动             }             else             {                 dueTime = (55 - minutes) * 60 * 1000;//到某个时间点的55分钟启动             }             WebTimerObj = new Timer(new TimerCallback(WebTimer_Callback), null, dueTime, Period);         }     }     /// <summary>     /// WebTimer的主函数     /// </summary>     /// <param name="sender"></param>     private void WebTimer_Callback(object sender)     {         try         {             if (Interlocked.Exchange(ref _IsRunning, 1) == 0)             {                 ExecuteMain();                 Times++;                 Times = (Times % 100000);             }         }         catch         {         }         finally         {             Interlocked.Exchange(ref _IsRunning, 0);         }     }     /// <summary>     /// 停止     /// </summary>     public void Stop()     {         if (WebTimerObj != null)         {             WebTimerObj.Dispose();             WebTimerObj = null;         }     }     #endregion }
二、在Global文件中调用所定义的方法
[u]复制代码[/u] 代码如下:
 void Application_Start(object sender, EventArgs e)     {         //在应用程序启动时运行的代码         WebTimer_AutoRepayment.Instance().Start(); //     }     void Application_End(object sender, EventArgs e)     {         //在应用程序关闭时运行的代码         WebTimer_AutoRepayment.Instance().Stop();//     }
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部