Reputation: 27
I am trying to create a script which does something say show a popup after 1 day. As far as I know I can do this using Thread.Stop or using System.Timers or many other ways. But the problem with each is that the computer has to be continuously running for each of these methods to give desired result at the time I want. Basically I want the script to start with installation of my program, wait for exactly 24 hours, then display a message box. If the computer is switched on at that time i.e. after 24 hours it should show the message box on next start up but only if 24 hours or more have passed. Please help, i am unable to find suitable solution for this. any help will be highly appreciated. I think that it may be achieved by getting the dateTime.Now and putting it in a file, and then compare current system time to the time in file every hour or so, and if 24 hours or more have passed, show the message box. Please help
Upvotes: 1
Views: 398
Reputation: 48696
If a message box is what you need to pop up, then you'll need a Windows Forms application. Here is the workflow of how it'll work:
TriggerDate
entry.TriggerDate
exists, pull this date and compare it to today's date and time. If the current date and time is past our TriggerDate
, display the message box. Recreate the TriggerDate
with the current date and time plus 24 hours.TriggerDate
does not exist, create it, filled with the current date and time plus 24 hours (e.g. DateTime.Now.AddHours(24)
). Threading.Thread.Sleep()
to sleep for 5 minutes.EDIT
Code will be something like this:
private const string TriggerFile = @"C:\TriggerData\trigger.txt";
private DateTime _triggerDate;
if (!File.Exists(TriggerFile))
{
using (StreamWriter sw = File.CreateText(TriggerFile))
{
sw.WriteLine(DateTime.Now.AddHours(24));
}
}
using (StreamReader sr = File.OpenText(TriggerFile))
{
_triggerDate = DateTime.Parse(sr.ReadToEnd());
}
while (true)
{
if (DateTime.Now >= _triggerDate)
{
MessageBox.Show(@"Alert!");
using (StreamWriter sw = File.CreateText(TriggerFile))
{
sw.WriteLine(DateTime.Now.AddHours(24));
_triggerDate = DateTime.Now.AddHours(24);
}
}
System.Threading.Thread.Sleep(60000*5); // Sleep for 5 minutes
}
You may not want to do while(true)
. You way want to implement a way to get out of the program.
Upvotes: 1
Reputation: 1787
I see two ways of achieving this :
Upvotes: 1
Reputation: 92
If I understand correctly, what you can use is a way to save the "start date". You can save the start date of the timer and read the value from your script, that way you can calculate if 24 hours or more has passed since the moment you assigned a value to the start date. You can use a simply TXT file to save the value.
Upvotes: 1