Skip to content

Instantly share code, notes, and snippets.

@hexbinoct
Created April 22, 2023 15:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hexbinoct/c2028f549ecc145acefb21de73e05295 to your computer and use it in GitHub Desktop.
Save hexbinoct/c2028f549ecc145acefb21de73e05295 to your computer and use it in GitHub Desktop.
public class WaitC
{
int m_hour, m_minute;
int m_waitMilliSeconds = 0;
public string TargetDailyTime {
get {
return $"{m_hour.ToString("00")}{m_minute.ToString("00")}";
}
set {
/*it will be a tring like 1030, 10 is hours, 30 is minutes,
this should always be in 24hrs format.*/
string s = value;
if (s.Length != 4)
throw new Exception("dude why is the passed string not a 4 length string with 24hr format???");
m_hour = int.Parse(s.Substring(0, 2));
m_minute = int.Parse(s.Substring(2));
}
}
public static void Start(string everydayTime, string logmsg, Action act)
{
WaitC c = new WaitC();
c.TargetDailyTime = everydayTime;
new Thread(() => {
while (true)
{
code.UIProc($"{logmsg} {c.TimeLeftString()}", null);
c.WaitTillNextTime();
try
{
act();
}
catch (Exception exp)
{
code.UIProc($"exception in waitc: logmsg '{logmsg}' >> {exp.ToString()}", null);
}
}
}) { IsBackground = true }.Start();
}
DateTime getNextTime(bool nextday)
{
var dn = DateTime.Now;
if (nextday)
dn = dn.AddDays(1);
var dtimestart = new DateTime(dn.Year, dn.Month, dn.Day, m_hour, m_minute, 0);
return dtimestart;
}
public TimeSpan getTimeToWait()
{
// start time to be something
var dn = DateTime.Now;
var dtimestart = new DateTime(dn.Year, dn.Month, dn.Day, m_hour, m_minute, 0);
DateTime nextTime;
if (dn > dtimestart)
{
// we need to start a timer till next day
nextTime = getNextTime(true);
}
else
{
nextTime = getNextTime(false);
}
var ts = (nextTime - DateTime.Now);
var sleepSeconds = ts.TotalSeconds;
m_waitMilliSeconds = (int)(sleepSeconds * 1000.0);
return ts;
}
public void WaitTillNextTime()
{
/*getTimeToWait() calculates when next the event is supposed to occur. */
getTimeToWait();
Thread.Sleep(m_waitMilliSeconds);
}
public string TimeLeftString()
{
var ts = getTimeToWait();
return $"{ts.Hours} hours, {ts.Minutes} minutes";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment