CodeGuru
Earthweb Search
Forums Wireless Jars Gamelan Developer.com
CodeGuru Navigation
Member Sign In
User ID:
Password:
Remember Me:
Forgot Password?
Not a member?
Click here for more information and to register.

Become a Marketplace Partner

jobs.internet.com

internet.commerce
Partners & Affiliates
















RSS Feeds

RSSAll

RSSVC++/C++

RSS.NET/C#

RSSVB

See more EarthWeb Network feeds

Home >> Visual C++ / C++ >> Miscellaneous >> Miscellaneous >> Task Scheduler


Basic class for using the Microsoft Task Scheduler
Rating: none

Michael Dunn (view profile)
April 24, 1999

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.


(continued)



[Sample scheduled task - 5K]

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).
  • 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 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        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.

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.

Demo project

Take the link below to download a demo project that illustrates using the CScheduledTask class.

Download demo project - 33KB

Download source - 9K

Date Last Updated: April 24, 1999

Tools:
Add www.codeguru.com to your favorites
Add www.codeguru.com to your browser search box
IE 7 | Firefox 2.0 | Firefox 1.5.x
Receive news via our XML/RSS feed







RATE THIS ARTICLE:   Excellent  Very Good  Average  Below Average  Poor  

(You must be signed in to rank an article. Not a member? Click here to register)

Latest Comments:
schedule method call - cheelam_mze (02/24/2005)
A COM object for Visual Basic - Legacy CodeGuru (03/30/2000)
Good Code...Would like to get some info - Legacy CodeGuru (08/31/1999)
Scheduler sample code including NT Security - Legacy CodeGuru (08/27/1999)
Win95 task list - Legacy CodeGuru (08/11/1999)

View All Comments
Add a Comment:
Title:
Comment:
Pre-Formatted: Check this if you want the text to display with the formatting as typed (good for source code)



(You must be signed in to comment on an article. Not a member? Click here to register)


JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
IBM Whitepaper: Innovative Collaboration to Advance Your Business
Internet.com eBook: Real Life Rails
Avaya Article: Call Control XML - Powerful, Standards-Based Call Control
Tripwire Whitepaper: Seven Practical Steps to Mitigate Virtualization Security Risks
Internet.com eBook: The Pros and Cons of Outsourcing
Go Parallel Article: Scalable Parallelism with Intel(R) Threading Building Blocks
Internet.com eBook: Best Practices for Developing a Web Site
IBM CXO Whitepaper: The 2008 Global CEO Study "The Enterprise of the Future"
Avaya Article: Call Control XML in Action - A CCXML Auto Attendant
Go Parallel Article: James Reinders on the Intel Parallel Studio Beta Program
IBM CXO Whitepaper: Unlocking the DNA of the Adaptable Workforce--The Global Human Capital Study 2008
Adobe Acrobat Connect Pro: Web Conferencing and eLearning Whitepapers
Go Parallel Article: Getting Started with TBB on Windows
HP eBook: Storage Networking , Part 1
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Go Parallel Video: Intel(R) Threading Building Blocks: A New Method for Threading in C++
HP Video: Is Your Data Center Ready for a Real World Disaster?
Microsoft Partner Portal Video: Microsoft Gold Certified Partners Build Successful Practices
HP On Demand Webcast: Virtualization in Action
Go Parallel Video: Performance and Threading Tools for Game Developers
Rackspace Hosting Center: Customer Videos
Intel vPro Developer Virtual Bootcamp
HP Disaster-Proof Solutions eSeminar
HP On Demand Webcast: Discover the Benefits of Virtualization
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Microsoft Download: Silverlight 2 Software Development Kit Beta 2
30-Day Trial: SPAMfighter Exchange Module
Red Gate Download: SQL Toolbelt
Iron Speed Designer Application Generator
Microsoft Download: Silverlight 2 Beta 2 Runtime
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
IBM IT Innovation Article: Green Servers Provide a Competitive Advantage
Microsoft Article: Expression Web 2 for PHP Developers--Simplify Your PHP Applications
Featured Algorithm: Intel Threading Building Blocks - parallel_reduce
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES