简体   繁体   中英

Run command if a program is run at a specific time of day?

I'd like to write a program that when executed will check for the system time, and if the system time is say... between 5pm and 8pm (or between 17:00 and 20:00) it will run a command, else it will just exit.

I'm having a harder time than i thought i would figuring out how to do this. all i've found out so far is that i can get the current date and time in a readable output from

DateTime.Now

but i have no idea how i can order the program to run commands depending on what time of day it is (regardless of date.) and using DateTime.Now to get the time then playing around with the string until it gives me a double or int for what time it is seems like a rather "uncool" way of doing it

It would be something like this, to check for example if current hour is between 17 and 20. Just change the values:

 if (DateTime.Now.Hour > 17 && DateTime.Now.Hour < 20)
 { 
   //Do stuff
 }

Edit: If you want to include the hours in the if sentence use >= <=

 if (DateTime.Now.Hour >= 17 && DateTime.Now.Hour <= 20)
 { 
   //Do stuff
 }

If you need finer control over the timing, such as including minutes in your "window", then use two TimeSpan's like this:

TimeSpan start = new TimeSpan(17, 30, 0); // 5:30 pm
TimeSpan stop = new TimeSpan(20, 45, 0); // 8:45 pm
if (DateTime.Now.TimeOfDay >= start && DateTime.Now.TimeOfDay <= stop)
{
    // ... do something ...
}

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