简体   繁体   中英

Constantly update Datetime variable in C# console application

I am trying to run a piece of code on user defined time but the datetime variable stores the value of time when i hit run and does not update to check if the time has changed.

static void Main(string[] args)
      {
          Console.WriteLine("please enter the date in m/d/y h/m/s am/pm     format ");
          DateTime bombDate = Convert.ToDateTime(Console.ReadLine());
          repeat:
          //DateTime bombDate = "7/27/2016 4:13:16 AM";

          DateTime now = DateTime.Now;
              if (bombDate == now)
              {
                  string _str = " this is a virus, you have been hit by a logic bomb  ...";
                  while (true)
                  {
                      foreach (char c in _str)
                      {
                          SendKeys.SendWait(c.ToString());
                          Thread.Sleep(200);


                      }
                        Thread.Sleep(3000);
                  }

              }

              else {
                  goto repeat;
              }

You can't match the two dates exactly, you're comparing the ticks here and the chances the two dates execute exactly at the same time Now matches the date is not that high. Since you're only specifying seconds from input then use this:

if ((bombDate - now).TotalSeconds < 0)

This matches the two dates even if there is it passed by up to less that 1 second.

Or you can just check if the needed time has passed:

if ((bombDate <= now))

I would post this as a comment but I can't.

Depending on what you're trying to do it might be worth to consider to write the program and just use a standard facility like the windows task scheduler to actually run it on specific conditions/times.

In addition goto is frowned up on by a lot of people for a good reason. Essentially you're creating a loop. Why not declare it as such? One possibility would be to use a loop which just counts the time (which is essentially what you're doing in your outer loop).

DateTime now = NULL;
while(bombDate != now){
    now = DateTime.Now;
}
// Other Code beginning with string _str =

On way to circumvent the timing problem would be to add another sleep after your initial assignment/before the loop. That way you would be sure that some time passed between the successive calls of DateTime.Now. Going for a finer resolution like user3185569 suggested might be better though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM