Schedule in C#



  • Good day! I have a table like that. Where: 1:1:4:0 - Day:hour:minutes:seconds

    введите сюда описание изображения

    We need to make the timer earn as shown on the table, if Час The timer's interval will be minutes and secondsif НеделяDay and hour

    string dbStr = row["shedule_dt_send_daytime"].ToString();
        string timenr = row["timer_name_ru"].ToString().ToUpper();
        DateTime dtbeg = Convert.ToDateTime(row["shedule_dt_beg"]);
        DateTime dtend = Convert.ToDateTime(row["shedule_dt_period_end"]);
          Console.Write(dbStr);
    
    //Разделяем строку на части
    string[] splitStr = dbStr.Split(':');
    
    
    
    
            // Получаем требуемый день недели.    
            int targetDayOfWeek = int.Parse(splitStr[0]);
            int targetHourofDay = int.Parse(splitStr[1]);
            int targetMinuteofHour = int.Parse(splitStr[2]);
            // получим русское имя дня недели
            string targetDayName = (new CultureInfo("ru-RU")).DateTimeFormat.DayNames[targetDayOfWeek % 7];
            Console.WriteLine("Таймер должен запуститься в " + targetDayName.ToUpper());
    
    
    
            // Получим текущий день недели
            int nowDayOfWeek = (int)DateTime.Now.DayOfWeek;
            string nowDayName = (new CultureInfo("ru-RU")).DateTimeFormat.DayNames[nowDayOfWeek % 7];
    
    
            DateTime startDay = DateTime.Now;
    
            if ((targetDayOfWeek != nowDayOfWeek) || (DateTime.Now > DateTime.Parse(dbStr.Substring(2))))
            {
                Console.WriteLine("Время запуска уже прошло. ");
                // Посчитаем разницу между днями 
                int waitDay = (nowDayOfWeek < targetDayOfWeek) ? targetDayOfWeek - nowDayOfWeek : (7 - nowDayOfWeek) + targetDayOfWeek;
                Console.WriteLine("Нужно подождать еще: {0} дней", waitDay);
                // Вычислим время запуска
                startDay = DateTime.Now.AddDays(waitDay);
            }
    
    
    
      // Вычислим время запуска
            DateTime startTime = new DateTime(startDay.Year, startDay.Month, startDay.Day, int.Parse(splitStr[1]), int.Parse(splitStr[2]), int.Parse(splitStr[3]));                
            if ((startTime > dtbeg) && (startTime < dtend))
            {
    
                    Console.WriteLine("Таймер будет запущен : {0}", startTime.ToString());
    
    
                // Узнаем разницу в миллисекундах, оставшуюся до запуска
    
                double waitTime_ms = (startTime - DateTime.Now).TotalMilliseconds;
                Console.WriteLine("До запуска осталось - {0} мc.", waitTime_ms);
    
    
    
                MyTimer myTimer = new MyTimer();
    
    
                myTimer.Interval = waitTime_ms;
                myTimer.s_id = Convert.ToString(row["shedule_id"]);
                myTimer.alg = Convert.ToString(row["meta_cod"]);
                myTimer.Elapsed += OnTimeout;
                myTimer.AutoReset = true;
                myTimer.datetime = Convert.ToDateTime(startTime);
                myTimer.Enabled = true;
    
    
    
                //while (true) 
                // { int Hour = 23; int Minute = 42; int Seconds = 00; 
                // if ((Hour == System.DateTime.Now.Hour) && (Minute == System.DateTime.Now.Minute) && (Seconds == System.DateTime.Now.Second)) 
    
    
    
            }
    
    
    }    
    
       // myTimer.Dt_Begin = Convert.ToDateTime(row["shedule_dt_beg"]);
       // myTimer.Dt_Period_End = row["shedule_dt_period_end"];
    
    
    
    
    
    
    
    
     // } 
    

    }

       }
    
    
    
       Console.WriteLine("Идёт запись...");
       Console.WriteLine("Нажмите ENTER чтобы выйти");
       Console.Read(); static void OnTimeout(object sender, System.Timers.ElapsedEventArgs e)
        {
    
            var s_id = ((MyTimer)sender).s_id.ToString();
            var alg = ((MyTimer)sender).alg.ToString();
            var date = ((MyTimer)sender).datetime;
            string st = "0";
            string com = "null";
            var beg = DateTime.Now;
            var end = DateTime.Now;
            var cr = DateTime.Now;
            var upd = DateTime.Now;
    
            //var comment = new[] { ((MyTimer)sender).comment.ToString() };
            //var beg = new[] { ((MyTimer)sender).Dt_Begin };
            //var end = new[] { ((MyTimer)sender).Dt_Period_End };
            //string upd = string.Format("UPDATE ALg_stack SET dt_create=GETDATE() WHERE id=(SELECT id from alg_stack)");
    
    
            string sql = string.Format("Insert Into Alg_stack" +
               "(shedule_id,metaAlg,datetime, st, comment, dt_beg, dt_end, dt_create, dt_update) Values( @s_id,@alg, @date, @st, @com, @beg, @end, @create, @upd)");
    
            using (SqlConnection cn = new SqlConnection())
            {
                cn.ConnectionString = @"Data Source=192.168.1.156;Initial Catalog=ihd_aktobe;User ID=sa;Password=Pa$$w0rd";
    
                cn.Open();
    
                using (SqlCommand cmd = new SqlCommand(sql, cn))
                {
    
                    cmd.Parameters.AddWithValue("@s_id", s_id);
                    cmd.Parameters.AddWithValue("@alg", alg);
                    cmd.Parameters.AddWithValue("@date", date);
                    cmd.Parameters.AddWithValue("@st", st);
                    cmd.Parameters.AddWithValue("@com", com);
                    cmd.Parameters.AddWithValue("@beg", beg);
                    cmd.Parameters.AddWithValue("@end", end);
                    cmd.Parameters.AddWithValue("@create", cr); 
                    cmd.Parameters.AddWithValue("@upd", upd);
    
    
                    cmd.ExecuteNonQuery();
                }
                cn.Close();
    
    
    
            }
    
    
    
        }
    



  • Sos, it's a conditionality. We're taking the data from the base and trying to get them to class. The class itself looks like this:

      public class TimerData
      {
        public TimerPeriod Period { get; private set; }
    
    public TimeSpan TimeSpan { get; private set; }
    
    private TimeSpan FormateTimeSpanToPeriod(int days, int hours, int minutes, int seconds)
    {
      switch (this.Period)
      {
        case TimerPeriod.Hour:
          return new TimeSpan(0, 0, minutes, seconds);
          break;
        case TimerPeriod.Week:
          return new TimeSpan(days, hours, 0, 0);
          break;
        default:
          throw new ArgumentOutOfRangeException();
      }
    }
    
    public TimerData(string period, string timings)
    {
      this.Period = period == "Неделя" ? TimerPeriod.Week : TimerPeriod.Hour;
      var parsed = timings.Split(':').Select(int.Parse).ToArray();
      this.TimeSpan = FormateTimeSpanToPeriod(parsed[0], parsed[1], parsed[2], parsed[3]);
    }
    

    }

    public enum TimerPeriod
    {
    Hour,
    Week
    }

    It's the minimum necessary data on the plate. Now, how do data from the plate turn into these classes and then create timers from class:

      var sqlData = new List<string[]>();
    sqlData.Add(new[] { "Час", "1:1:4:0" });
    sqlData.Add(new[] { "Неделя", "1:0:0:0" });
    var td = sqlData.Select(s => new TimerData(s[0], s[1])).ToList();
    foreach (var timerData in td)
    {
    var timer = new Timer(timerData.TimeSpan.TotalMilliseconds);
    timer.Start();
    }

    For sqlData You must use your own, your source of data for these very lines.
    In the end, td We have a data list for the timers.
    Well, then, I'm sorry I didn't understand your magic with the timers, so I just... foreach a timer may be set up for each record, the interval of which is easy timerData.TimeSpan.TotalMilliseconds♪ Other parameters inside foreach It tastes good.


Log in to reply
 


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2