Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a windows service that archives files from a paticular folder. I want the program to run everday at a specific time. I can do that using the task scheduler. what I want to do is to schedule the task without actually assessing the windows task scheduler GUI. Maybe a batch script that schedules the program to run every day even when the system is on sleep or maybe something else i can do? does anyone have an idea of how this thing can be implemented?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
124 views
Welcome To Ask or Share your Answers For Others

1 Answer

The solution is pretty basic . so the thing is that instead of using the task scheduler we are creating a scheduler itself in our code so there is a thread that will be created that will always be checking for the time that I want my actual code to run and once the current time is the time that I want the method to run it will trigger the main program(in the example the method I want to trigger is named ArchiveFile) . so first in the OnStart I am setting a new timer and want it to fire 24x7,every hour. then in the timer_elapse i want to check if the current time is the time I want my method to execute and if true it will call the method that I want to execute.(in this example I have set the time to be 9 pm or 21 hours)

    protected override void OnStart(string[] args)
    {
        timer = new System.Timers.Timer();                                        
        timer.Interval = 36000;                                                   // that fires every hour    
        timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);    //calling the elapse event when the timer elapses
        timer.AutoReset = true;                                                   // AutoReset is set to true as we want the timer to fire 24x7 so that the elapse event is executed only at the requried time  
        timer.Enabled = true;                                                                                                   

    }
    protected void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)       //everytime the elapse event occurs the TimeCheck method will be called 
    {
        TimeCheck();    
    }

    public void TimeCheck()    //method to check if the current time is the time we want the archiving to occur
    {

        var dt = DateTime.Now.Hour;
        if(dt==21)
        {
            Archivefile();
        }

    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...