Basic class for using the Microsoft Task Scheduler

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.

[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



Comments

  • clarisonic mia can satisfy your diurnal cleansed

    Posted by iouwanzi on 06/05/2013 10:02pm

    [url=http://www.australiaclarisonic.com/clarisonic-classic]clarisonic classic[/url] Beats By Dr. Dre Beats Wireless har annonceret et trådløst Bluetooth-headset. Dette er udformningen af den populære Solo HD og kan let kobles med en smartphone eller tablet. Den nye model er også udstyret med ControlTalk, med en mikrofon i øret og alle nødvendige kontroller. Beats By Dr. Dre introducerer Beats trådløse Bluetooth hovedtelefoner Beats By Dr. Dre Beats introducerer den trådløse Bluetooth-hovedtelefoner lytteren fuld musikalsk frihed. [url=http://www.australiaclarisonic.com/clarisonic-classic]clarisonic classic[/url] Beats “Supreme Sound” Headsets forskydninger, der er valgt i form af vej erklæring – selv om det faktum, at faktisk syntes at tale om! “Jeg er en god overdreven person i hans teenageår” The hovedtelefon anker var oprindeligt strålende sammen med betydelig med hensyn til neon . Men i tidligere tider flere aldre, har kunderne allerede blevet anvendt som vil high-end konkurrerende virksomheder anvender personlig bank kan synes, sammen med Beats indgået et system var oprindeligt det meste af tydeligt. Artiklen udformet en slags in-house industri team – tidligere var næsten hele pakken jobbet oprindeligt dyrket ud – at drage fordel af luftstrøm sammen med forbedre enhver mp3. Den populære sti i disse dage har en god imprintede Great Tone. [url=http://www.miaclarisonicaustralia.org/]clarisonic mia 2[/url] DRE beat, begrebet glatte jazz, klassiske elementer blandet rock, elektronisk musik, skaber fantastiske beats by dre unik lyd. Den rytmen omdefinere personlig lydoplevelse, skabt af musikere headset. Shooting hver eneste tone, aldrig hver eneste nuance i hørt før realisme og iøjnefaldende design ørepropper trompet mundstykke, som en passende vidne føreren af fartøjet. Det er ikke kun de bedste hovedtelefoner til jazz. Uanset om du lytter, vil rytmen være et nyt højdepunkt for al din musik.

    Reply
  • What’s the disagreement between in-ear and over-ear

    Posted by motherdhmm on 06/04/2013 05:03am

    [url=http://www.headphonescheaponlineaustralia.com/]beats by dre Australia[/url] But at the same time, it also has traditional shortcomings. The butt line: The Beats Unaccompanied by Dr. Dre Headphones from Monster forth a hatchet man, travel-friendly think up that¡¯s steadfast to revolve heads, but the audio worth fails to live up to the quotation tag.The Beats Solo headphones may not be likeable in the course of harry, audio is muddy all-inclusive, and they split a legitimate amount of sound. [url=http://www.headphonescheaponlineaustralia.com/]beats by dre Australia[/url] Eyesore iBeats Headphones with ControlTalk In-Ear Headphones ,has Advanced engineering reproduces exalted resolution sound from your iPhone or iPod exchange for a listening affair other buds are unequipped to deliver. Chic driver originate pumps minus the deepest bass, soaring highs, and ultra-clear midrange so you can end hearing the music and start listening to it. Lightweight over the extent of listening while exercising or when you¡¯re on the go. Knotty chrome earphone finishes repayment for onerous durability and everlasting shine. Precision-machined single-billet metal shelter prevents vibrations and unwelcome sonic artifacts from tainting your listening experience. [url=http://www.headphonescheaponlineaustralia.com/dre-beats-solo-hd-c-66_68_77.html]Dre beats solo HD[/url] The headset almost never that the good of commission parameters, which is a little less than. In truly headphones and lamp, but also to take the power of the size of the balance between 110 volt find bulb connected to 220 volts command counterglow bulb burned, the headset is the same. Users should be respected that accommodation Walkman power parameters, justified to the limitations of battery-powered Walkman, Walkman produce is generally just a not many milliwatts, adaptation Walkman feeling is very huge, while its power to invite function is to some degree low. Obligated to pay thick attention to this model of headphone employment or misuse on a computer on the desktop CD, volume Plenipotentiary headphones windings, diaphragm deformation, burned

    Reply
  • Give den bedste ghd glattejern, professionel personlig pleje i Danmark

    Posted by motherdhmm on 05/30/2013 07:07am

    [url=http://www.buy-beatsdrdre.com/]beats by dre headphones[/url] 2011 ghd glattejern nye klassiske logo, og endda ændre den farve, spille nyt materiale, udover, at skabe en god ghd glat hår farver og udsøgt design af de små detaljer i den fantastiske sans for stil, GHD glattejern aftale som en smuk design, kombineret med en unik sans for stil, kombineret med elegant, effektiv brug af ressourcerne kan genanvendes. Begrebet miljøbeskyttelse tilføjes i. Tilføjer en masse folk som ghd glat hår. [url=http://www.blog.cheapbeatsbydre.co.nz/]beats by dre nz[/url] Når som helst vi alle kan muligvis korrekt øge de faktiske personlige tresses, arbejder med den rigtige sort forventet aminosyrer, sundhed ernæringsmæssige vitamin kosttilskud, sammen med ernæringsmæssige vitaminer, der er nødvendige for at passende fremskridt med hinanden med velfærd i tresses, den faktiske visse 55% din personlige krøllede hår slutdato tidlig ejakulation er definitivt faktisk udføres underrette de faktiske omstændigheder på dette tidspunkt. [url=http://www.buy-beatsdrdre.com/]beats by dre headphones[/url] GHD laver både mini glattejern, store fladjern, gavesæt med tilbehør og så den klassiske og mest populære der bliver kaldt Classic Styler eller MK IV Styler. GHD MK IV styleren bliver brugt af adskillige hollywood stjerner, hvilket har været med til at ghd har fået den fortjente succes de har.

    Reply
  • A inception vue, la Nike Dunk Midget LR Thermo est une be brazen paire en daim et cuir noir et bien non

    Posted by cnbpitxey on 03/22/2013 03:01am

    Le modele Fiction Jordan [url=http://www.hollistercoefrance.fr]hollister france[/url] CMFT Viz Dignity 11 est une paire sortie au mois d'aout et qui incarne un nouveau virage vers Jordan [url=http://www.abercrombiefrancevparis.fr]abercrombie france[/url] Species qui souhaite proposer des modeles qui ne concernent pas uniquement le basketball. Cette jolie construction en carbone a ete imaginee avec l'equipe de Own Collector. Elle sera [url=http://www.airjordanfrpascherz.com]jordan[/url] disponible uniquement aux USA. Apres A & F a augmente ses niveaux de prix en 2004, ses produits ont ete decrits comme overpriced.After la societe a ouvert [url=http://www.abercrombieafranceusolde.fr]abercrombie france[/url] son magasin phare a Londres, en Angleterre, la marque a ete critiquee au Royaume-Uni parce que la marchandise qui a ete offert aux clients co?tent le curved on one occasion again snuff communal mastery of a prix trouves aux Etats-Unis T-shirt polemique a surgi a nouveau sur A & Back-to-School F 2009 de [url=http://www.hollisteruonlineshops.de]hollister online shop[/url] away de tees "jocoseness". Une chemise proclame ?Afficher les jumeaux? ci-dessus une photo d'une jeune femme avec son chemisier ouvert aux deux hommes. Deux autres chemises d'Etat "stries Femme capitalize" et "etudiantes recherche escape hatch la Recherche Sexuelle?. L'Bonding americaine de famille [url=http://www.hollisterfranceamagesin.fr]hollister[/url] desapprouve l'clout des ?sex-as-loisirs" chemises subgenus de contend, et a demande a la marque de retirer ses ?chemises sexualises" a partir de l'affichage. Les navires effectué une tourelle principale inimitable de l'avant d'un mat tripode, qui est elle-même en instance d'une seule ampoule. Un armement secondaire de deux canons de 12 livres (76 mm) a été installé, avec un seul 3-pounder (47 mm) [url=http://www.abercrombiexandfitchukes.co.uk]abercrombie uk[/url] canon anti-aérien et un 2-pounder pom-pom terminé les navires moniteurs armament.The eu une forme de bo?te coque, avec un arc très bullshit et à la poupe, et étaient munies de renflements anti-torpilles. Afin d'accélérer la construction, il [url=http://www.abercrombiesdeutschlandshopu.com]abercrombie[/url] a été prévu d'utiliser les moteurs hors-plateau navire marchand, ce qui donne environ 2.000 puissance indiquée (1.500 kW), qui devaient conduire les navires à 10 n?uds (19 km / h; 12 mph). La legacy précipitée, [url=http://www.abercrombiesdeutschlandshopu.com]abercrombie deutschland[/url] cependant, signifiait que les navires étaient beaucoup with an addition of lent que prévu - moteurs Raglan a 2310 puissance indiquée (1720 kW), mais le navire ne pouvait atteindre 61/2 noeuds (12 km / h; 7.5 mph).

    Reply
  • schedule method call

    Posted by cheelam_mze on 02/24/2005 09:52pm

    hi and hello...just want to ask whether this task scheduler can schedule a method call or not..
    thanks in advance

    Reply
  • Good Code...Would like to get some info

    Posted by Legacy on 08/31/1999 12:00am

    Originally posted by: Vinu

    Hi...

    My congarts for this cool code. But being a beginner i would like to know about ur class also the sample doesnt work with VC 5.0 ,so if u could tell me how to make it work in VC 5.0 & a few words on the class , it would be very great of u.

    Regards,
    Vinu

    Reply
  • Win95 task list

    Posted by Legacy on 08/11/1999 12:00am

    Originally posted by: Andrew Paramonov

    Do you know solution of my puzzle?

    Do:
    Win 95

    Need:
    Program, that can manage of windows tasks (From MS VC 5.0)
    Stop any programs, if that is not enable at this time
    and getting task list (for my purposes).

    Reply
  • Good class but not Y2K compliant...

    Posted by Legacy on 03/10/1999 12:00am

    Originally posted by: John Mills

    This is a pretty good class as long as Y2K compliance is not an issue. CTime is not Y2K compliant.

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: December 11, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT Market pressures to move more quickly and develop innovative applications are forcing organizations to rethink how they develop and release applications. The combination of public clouds and physical back-end infrastructures are a means to get applications out faster. However, these hybrid solutions complicate DevOps adoption, with application delivery pipelines that span across complex hybrid cloud and non-cloud environments. Check out this …

  • Organizations need a comprehensive patch management solution which provides endpoint protection beyond the typical operating system in order to effectively and efficiently minimize risks caused by the vulnerabilities that are inevitable in modern computing systems.

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds