定时器timer传参及使用demo

定时器timer传参及使用demo
 public  class  Tuesday
 {
     //私有变量timer
     private System.Timers.Timer timer;
     private readonly ISqlSugarClient db;
     public Tuesday(IConfiguration configuration)
     {
         //sqlsugar 配置连接字符串
         SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
         {``
             ConnectionString = configuration["ConnectionStrings:SqlConnection"],//连接符字串
             DbType = DbType.Oracle,
             IsAutoCloseConnection = true,
             InitKeyType = InitKeyType.Attribute,
         });
         string conn = configuration["UpdateDay:UpdateTime"];
   
         timer = new System.Timers.Timer();
         this.db = db;
         // 设置定时器的间隔为 的时间,以天为单位
          double interval = TimeSpan.FromDays(1).TotalMilliseconds;
      
         timer.Interval = interval;

         // 设置定时器的触发事件
         timer.Elapsed += (sernder ,e) => Timer_Elapsed(conn, e);
//当 AutoReset 属性设置为 true 时,定时器将在每次间隔过去后自动重新启动,即定时器将持续触发 Elapsed 事件,按照设定的间隔进行操作。这通常用于周期性的定时任务,比如每隔一段时间执行一次。
         timer.AutoReset = true;
//当 Enabled 属性设置为 true 时,定时器处于启用状态,它会按照设定的间隔触发 Elapsed 事件。
当 Enabled 属性设置为 false 时,定时器被禁用,不会触发 Elapsed 事件,即使 AutoReset 为 true,也不会自动重新启动。
         timer.Enabled = true;
         // 启动定时器
         timer.Start();
     }


     public  void Timer_Elapsed(object sender, ElapsedEventArgs e  )
     {
         DayOfWeek day = (DayOfWeek)sender;
         if (DateTime.Now.DayOfWeek == day)
         {
             
             var departmentsToProcess = db.Queryable()
                 .ToList();

             List spdList = new List();

             string currentDate = DateTime.Now.ToString("yyyyMMddHHmmss");

             foreach (var department in departmentsToProcess)
             {
                 T_SPD_COUNT_ORDER tspd = new T_SPD_COUNT_ORDER();
                 tspd.BILL_NO = "PA" + currentDate;
                 tspd.BILL_DATE = currentDate;
                 tspd.DEPARTMENT_NO = department.DEPARTMENTNO;
                 tspd.TARGETDEPARTMENTNO = department.DEPARTMENTNAME;
                 tspd.FLAG = 0;
                 tspd.CREATE_DATE = DateTime.Now;
                 spdList.Add(tspd);
             }

             if (spdList.Any())
             {
                 // 使用批量插入
                 db.Insertable(spdList).ExecuteCommand();
             }
         }

     }
 }

你可能感兴趣的:(windows)