good day! I have a table like this. Where: 1: 1: 4: 0 - day : hour : minutes : seconds

enter image description here

It is necessary to make the timer work as shown in the table, with the condition that if Час the interval of the timer will be minutes and seconds , if Неделя the 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(); } } 
  • nobody wants to help? - propro17
  • I did not quite understand what you twist. On each line you need to run on a timer? Why is not one timer with a minimum period then? PS: the more specific the question, the easier it is to answer it, you have no question, you just have a piece of code and you do not understand if there is a problem. - Monk
  • I updated the question - propro17
  • one
    Once again, what are you trying to do and what does not work? Judging by the first lines of the code, you are trying to build a mapping, and judging by the text - the problem with timers. Describe the problem as accurately as possible, so that without reading all your code it was clear what did not work out and how you tried to do it. I still see a bunch of suspicious calls to row on string keys and nothing more. - Monk
  • there is one table that has columns name_ru and dt_send there is a timer that writes data to another table. The timer should work with the condition: if an час selected in name_ru , then the timer should work in minutes, if it is selected from the Неделя column, then the timer should work by day and hour. Now it is clear? - propro17

1 answer 1

Itax, which conditionally turned out. We take the data from the database and try to parse them into the 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 } 

This is the minimum required data on the plate. Now, how to turn the data from the table into these classes, and then create timers from the classes:

  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(); } 

Instead of sqlData you should use something different, your own data source for these very lines. As a result, in td we have a list of data for timers. Well, then, unfortunately, I did not understand your magic with timers, so just in foreach you can create a timer for each entry, the interval of which is easily obtained from timerData.TimeSpan.TotalMilliseconds . The remaining parameters inside the foreach customized to taste.

  • this.Period = period == "Неделя" ? TimerPeriod.Week : TimerPeriod.Hour; and what does it mean? - propro17
  • I just need to add terms. It is possible with the switch . Do not tell me in my code where to put the conditions? - propro17
  • For example, switch case: "Неделя" ... - propro17
  • @ propro17 why I asked you to clarify the question. For your question, the only thing that is obvious is that you need to change the total TimeSpan by period in another column. This is done. What else do you expect from the code - it is not clear. - Monk