Search code examples
c#timerstartup

Application showing in process tree on startup but not running actually


I created a program to check system time, write that time to a file, and if 1 hour has passed do something by comparing the time in the file and the present system time. I chose this approach beause i expected this to work even if computer was turned off during this period. I have already added the program to startup in registry, the program shows up on restart in taskmanager processes tab, but does not work as expected. If the computer is not restarted or shutdown during this period, it works fine. Please tell me, what am I doing wrong. My code is

    static void Main(string[] args)
    {
        try
        {
        RegistryKey reg = Registry.CurrentUser.OpenSubKey("SOFTWARE\\MICROSOFT\\WINDOWS\\CURRENTVERSION\\RUN", true); // Add to registry to startup automatically in case of system shutdown or restart.
        reg.SetValue("Notifier", "\"" + Application.ExecutablePath.ToString() + "\"");

        }
        catch
        {
        MessageBox.Show("There was an error switching the registry key");
        }

        string Trigger = "time";
        DateTime _triggerDate;
        if (!File.Exists(Trigger))
        {
            using (StreamWriter sw = new StreamWriter(Trigger,true))
            {
                sw.Write(DateTime.Now.AddHours(1));
            }
        }
        using (StreamReader sr = File.OpenText(Trigger))
        {
            _triggerDate = DateTime.Parse(sr.ReadToEnd());

        }
        while (true)
        {
            if (DateTime.Now >= _triggerDate)
            {
                doSomething();
                break;

            }
            else
            {
                System.Threading.Thread.Sleep(120000); // Sleep for 2 minutes
            }
        }
    }

Please clarify what is going wrong.. I have checked registry also


Solution

  • Try to set an absolute path for your trigger time file. If you just call it "time" it is saved relatively to the working directory you started the program from. The autostart of windows will be started in another directory and so your trigger time file will not be found.