Click here to Skip to main content
15,867,308 members
Articles / Web Development / HTML
Article

Basic class for using the Microsoft Task Scheduler

Rate me:
Please Sign up or sign in to vote.
4.95/5 (12 votes)
29 Nov 19995 min read 142.5K   3.7K   61   20
  • Download demo project - 23 Kb
  • Download demo files - 9 Kb
  • Sample Image

    Overview

    Microsoft developed a full-featured scheduler for IE 4, IE 5, Win 98, and NT 5. From looking at all the task options available (three property pages, plus an "advanced" dialog) you could imagine that programming the scheduler is quite a chore. And you'd be right. I developed the CScheduledTask class to help you create very simple tasks and understand the basics of using the scheduler.

    View changes and bug fixes.

    There is plenty of room for improvement in this class. This was done purposely on my part -- making a class to implement all the features of the scheduler would have amounted to rewriting the scheduler UI, which I really didn't want to do (for free ;)). As it currently stands, CScheduledTask can create and delete events from the scheduler. Tasks can have simple schedules, namely one time only, daily, weekly, or monthly.

    CScheduledTask was written with MSVC 6.0 on Win 98. It should work OK in Unicode, although I haven't tested it. I do use a couple of 6.0-specific functions, such as CTime::GetAsSystemTime() and CString::Delete(), so in order to build with MSVC 5.0, you'd need to convert those sections back to use MFC 4.2 functions. You would also need the INetSDK or Platform SDK installed, because you need to link with MSTASK.LIB for the scheduler GUIDs and #include MSTASK.H for the interfaces.

    Please note that this class does not interface with the AT service, the default scheduler on NT 4 and earlier.

    Creating a task

    So, you want to schedule a program, eh? Here is the information you'll need to provide to CScheduledTask:

    • Program name: The fully-qualified path to the program (required).
    • Parameters: Any command-line parameters you want to pass to the program (optional).
    • Starting directory: The starting directory for the program (optional).
    • Account and password: The account the task will run under, and the account's password (required for NT only).
    • Starting date and time: The date and time a one-time task will run, or the beginning date and time for a repeating task (required).
    • Ending date: The last day that a repeating task will run (optional, N/A for one-time tasks). If this is not set for a repeating task, the task will repeat indefinitely.
    • Frequency: One time, daily, weekly, or monthly (required).
    • Comment: A string to be displayed in the task's property sheet in the scheduler UI (optional).

    There's a little catch when creating a weekly repeating task: if you want the task to repeat on Mondays, the starting date must be a Monday. Similarly, for monthly tasks, if you want the task to run on the 20th, the starting date must be a 20th.

    The CScheduledTask member functions for doing all this are listed below:

    void SetProgram ( LPCTSTR szProgram )
    void SetParameters ( LPCTSTR szParams )
    void SetStartingDir ( LPCTSTR szDir )
    void SetAccountName ( LPCTSTR szAccount )
    void SetPassword ( LPCTSTR szPassword )
    void SetStartDateTime ( const CTime& timeStart )
    void SetStartDateTime ( const SYSTEMTIME& timeStart )
    void SetEndDate ( const CTime& timeEnd )
    void SetEndDate ( const SYSTEMTIME& timeEnd )
    void SetFrequency ( CScheduledTask::ETaskFrequency freq )
    void SetComment ( LPCTSTR szComment )

    Note that there are two functions for setting the starting time, and two for the ending date. The two overloads let you pass in a CTime or SYSTEMTIME, depending on whatever format you use in your code.

    ETaskFrequency is an enumeration that has the following values:

    enum ETaskFrequency
        {
        freqOnce, freqDaily, freqWeekly, freqMonthly
        };

    Once you've set all the relevant info, call the SaveTask() function:

    HRESULT SaveTask ( LPCTSTR szTaskName, BOOL bFailIfExists = FALSE )

    The return value is S_OK if the save was successful. If you call this function before setting a required parameter (i.e., task name, start date/time, or frequency), the return value is E_FAIL. If a scheduler COM method fails, the HRESULT returned is the error returned by the last COM method that was called. In the debug version, CScheduledTask will display a trace message listing which method failed.

    The bFailIfExists parameter determines if SaveTask() will bail out if a task with the given name already exists. The default behavior is to replace an existing task.

    Deleting a task

    Deleting a task is quite easy - just call the DeleteTask function:

    static HRESULT DeleteTask ( LPCTSTR szTaskName )

    Note that this is a static function, and it works independently of everything else in the class. This function also returns an HRESULT, similar to SaveTask().

    Other functions

    If you have the need to clear out the contents of a CScheduledTask object, call the Reset function:

    void Reset();

    I have also included accessor functions to return the various task parameters. They are:

    BOOL           GetStartDateTime ( CTime& ) const;
    BOOL           GetEndDate ( CTime& ) const;
    ETaskFrequency GetFrequency() const;
    CString        GetProgram() const;
    CString        GetParameters() const;
    CString        GetStartingDir() const;
    CString        GetAccountName() const;
    CString        GetComment() const;

    These functions are there for the sake of completeness, they were easy to write, and they also provide a starting point for future enhancements, such as the ability to enumerate through existing tasks in the scheduler.

    GetStartDateTime() and GetEndDate() return a BOOL indicating if the corresponding date/time has been set. They return TRUE if the date/time is set, or FALSE if not. GetFrequency() returns the special value freqUnset if no frequency has been set. The remaining functions return an empty string if the corresponding item has not been set. Note that there is no GetPassword() function, because the Task Scheduler API doesn't provide a way to retrieve the password.

    Updates

    April 18, 1999: Version 1.1 has these changes:

    • Fixed some compile errors when building for Unicode. Thanks to Chris Maunder for providing the fixes!
    • Fixed SaveTask() to properly check for an existing task. The change was necessary because I worked around a bug in IE 4, but the bug was fixed in IE 5, resulting in my code breaking when run on IE 5.
    • Added a #pragma to automatically link with mstask.lib, so you don't have to remember to do that in your app's project settings.
    • Added a check after the CoCreateInstance() call to see if the error is REGDB_E_CLASSNOTREG. If so, I display a nicer trace message explaining that you don't have the scheduler installed.

    November 27, 1999: Version 1.2 has these changes:

    • Added functions to set an account and password for a task, so the task will run on NT.

    License

    This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

    A list of licenses authors might use can be found here


    Written By
    Software Developer (Senior) VMware
    United States United States
    Michael lives in sunny Mountain View, California. He started programming with an Apple //e in 4th grade, graduated from UCLA with a math degree in 1994, and immediately landed a job as a QA engineer at Symantec, working on the Norton AntiVirus team. He pretty much taught himself Windows and MFC programming, and in 1999 he designed and coded a new interface for Norton AntiVirus 2000.
    Mike has been a a developer at Napster and at his own lil' startup, Zabersoft, a development company he co-founded with offices in Los Angeles and Odense, Denmark. Mike is now a senior engineer at VMware.

    He also enjoys his hobbies of playing pinball, bike riding, photography, and Domion on Friday nights (current favorite combo: Village + double Pirate Ship). He would get his own snooker table too if they weren't so darn big! He is also sad that he's forgotten the languages he's studied: French, Mandarin Chinese, and Japanese.

    Mike was a VC MVP from 2005 to 2009.

    Comments and Discussions

     
    QuestionSchedule task without user password Pin
    Miraz Zaidi21-Jun-14 3:35
    Miraz Zaidi21-Jun-14 3:35 
    GeneralDoesnt work on WinXP Pro Pin
    Michael B Pliam29-Jun-08 10:43
    Michael B Pliam29-Jun-08 10:43 
    QuestionHow to enable/disable task Pin
    dhaval_001131-Mar-08 19:59
    dhaval_001131-Mar-08 19:59 
    GeneralExactly what I needed! Pin
    Paul Roberts17-Oct-07 8:30
    Paul Roberts17-Oct-07 8:30 
    Absolutely superb code, and very well commented. I was up and running in with it in no time. Many thanks Smile | :)
    GeneralSetting Flags Pin
    #93709-Jul-07 8:44
    #93709-Jul-07 8:44 
    GeneralRe: Setting Flags Pin
    #937019-Jul-07 8:13
    #937019-Jul-07 8:13 
    QuestionHow to create "Hidden Tasks"? Pin
    tee_jay11-Mar-06 1:15
    tee_jay11-Mar-06 1:15 
    AnswerRe: How to create "Hidden Tasks"? Pin
    tee_jay11-Mar-06 2:32
    tee_jay11-Mar-06 2:32 
    AnswerRe: How to create "Hidden Tasks"? Pin
    Michael Dunn12-Mar-06 14:17
    sitebuilderMichael Dunn12-Mar-06 14:17 
    QuestionRe: How to create "Hidden Tasks"? Pin
    tee_jay12-Mar-06 18:51
    tee_jay12-Mar-06 18:51 
    GeneralDon't forget to AfxOleInit() Pin
    kbomb98730-Aug-04 18:25
    kbomb98730-Aug-04 18:25 
    GeneralTasks will not run on XP with blank PWD : Solution Pin
    Monty231-Jul-04 19:23
    Monty231-Jul-04 19:23 
    GeneralRe: Tasks will not run on XP with blank PWD : Solution Pin
    Anonymous25-Sep-05 16:22
    Anonymous25-Sep-05 16:22 
    GeneralRe: Tasks will not run on XP with blank PWD : Solution Pin
    Mustafa Demirhan18-Jul-06 12:45
    Mustafa Demirhan18-Jul-06 12:45 
    QuestionHow can I download zip file? Pin
    fish_bird26-Apr-04 16:29
    fish_bird26-Apr-04 16:29 
    AnswerRe: How can I download zip file? Pin
    Michael Dunn27-Apr-04 4:22
    sitebuilderMichael Dunn27-Apr-04 4:22 
    QuestionMay I use the code for my own program? Pin
    LeonCheong20-Feb-03 1:57
    LeonCheong20-Feb-03 1:57 
    GeneralImplementing a callback Pin
    18-Feb-02 14:44
    suss18-Feb-02 14:44 
    GeneralChange a scheduled task Pin
    Albert van Peppen3-Dec-01 6:04
    professionalAlbert van Peppen3-Dec-01 6:04 
    GeneralExcellent! Pin
    Jon Sagara16-Nov-01 13:55
    Jon Sagara16-Nov-01 13:55 

    General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

    Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.