examples/SysLibs/TaskSchedulerExample/taskscheduler.cpp

Go to the documentation of this file.
00001 /*
00002 Copyright (c) 2007-2010 Nokia Corporation and/or its subsidiary(-ies). All rights reserved.
00003 
00004 Redistribution and use in source and binary forms, with or without
00005 modification, are permitted provided that the following conditions are met:
00006 
00007 * Redistributions of source code must retain the above copyright notice, this
00008   list of conditions and the following disclaimer.
00009 * Redistributions in binary form must reproduce the above copyright notice,
00010   this list of conditions and the following disclaimer in the documentation
00011   and/or other materials provided with the distribution.
00012 * Neither the name of Nokia Corporation nor the names of its contributors
00013   may be used to endorse or promote products derived from this software
00014   without specific prior written permission.
00015 
00016 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
00017 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
00018 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
00019 DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
00020 FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
00021 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
00022 SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
00023 CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
00024 OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
00025 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
00026 
00027 Description: 
00028 This is simple example code that demonstrates the use of task scheduler. 
00029 The code demonstrates how to,
00030 1) Connect and register with the task scheduler
00031 2) Create a persistent schedule
00032 3) Add tasks to it
00033 4) Execute the schedule
00034 5) Delete the schedules and the tasks associated with them after
00035 verifying that they are the schedules created by us.
00036 6) Create a transient schedule
00037 7) Add task to the transient schedule, edit the schedule and execute it 
00038 */
00039 
00040 
00041 
00042 
00043 
00047 #include "taskscheduler.h"
00048 #include <e32std.h>
00049 #include <schinfo.h>
00050 #include <e32base.h>
00051 
00052 _LIT(KTaskName,"MyTaskName\n");
00053 
00054 _LIT(KTitle, "Task Scheduler example");
00055 _LIT(KTextPressAKey, "\nPress any key to step through the example\n");
00056 _LIT(KExit,"\nPress any key to exit the application");
00057 _LIT(KPressAKey,"\nPress any key to continue\n");
00058 
00059 _LIT(KConnect, "\nConnecting the client to the task scheduler server");
00060 _LIT(KRegisterClient,"\nRegistering the client\n");
00061 _LIT(KCreateSchedule,"Creating a persistent schedule\n");
00062 _LIT(KCreateTask,"Creating task for the schedule\n");
00063 
00064 _LIT(KPersistentWait,"Waiting for the persistent task to complete. This will take 20 seconds\n");
00065 _LIT(KDone,"Task complete \n");
00066 _LIT(KTransientSchedule,"A transient schedule");
00067 _LIT(KTransientWait,"Waiting for the transient task to complete. This will take 20 seconds\n");
00068 
00069 _LIT(KCreateTransient,"\nCreating a transient schedule with non-repeating task\n");
00070 _LIT(KDeleteAllTasks,"\nDeleting all the persistent tasks scheduled by this exe");
00071 _LIT(KDeleteAllSchedules,"\nDeleting all schedules created by this exe\n");
00072 _LIT(KTask, "Number of task(s) scheduled by us is(are) %d\n");
00073 _LIT(KExists, "The tasks scheduled exist\n");
00074 _LIT(KOtherTask,"Error! Unexpected schedules not scheduled by this exe exist\n");
00075 
00080 CTaskSchedule* CTaskSchedule::NewLC()
00081         {
00082         CTaskSchedule* schedule = new(ELeave) CTaskSchedule();
00083         CleanupStack::PushL(schedule);
00084         schedule->ConstructL();
00085         return schedule;
00086         }
00087         
00091 CTaskSchedule::CTaskSchedule()
00092         {
00093         }       
00094 
00095 void CTaskSchedule::ConstructL()
00096         {       
00097         iConsole = Console::NewL(KTitle,TSize(KConsFullScreen,KConsFullScreen));
00098         iConsole->Printf (KTextPressAKey);
00099         iConsole->Getch ();
00100         }
00101 
00105 CTaskSchedule::~CTaskSchedule()
00106         {
00107         iScheduler.Close();
00108         iConsole->Printf(KExit);
00109         iConsole->Getch();
00110         
00111         delete iConsole;
00112         }
00113 
00120 void CTaskSchedule::ConnectAndRegisterL()
00121         {
00122         
00123         // Connect to the scheduler server
00124         iConsole->Printf(KConnect);
00125         User::LeaveIfError(iScheduler.Connect());
00126         
00127         _LIT(KTaskExec,"Taskexecutor");
00128         TFileName filename;
00129         filename.Append(KTaskExec);
00130         
00131         // Register with the scheduler
00132         iConsole->Printf(KRegisterClient);
00133         
00134         // A priority value
00135         const TInt priority = 3;
00136         User::LeaveIfError(iScheduler.Register(filename, priority));
00137         
00138         }
00139 
00146 void CTaskSchedule::PersistentScheduleL()
00147         {
00148         
00149         iConsole->Printf(KCreateSchedule);              
00150         TSchedulerItemRef scheduleHandle;
00151         TTime time;
00152         time.UniversalTime();
00153         
00154         // Assign an offset of 20 seconds. TTimeIntervalMinutes, 
00155         // TTimeIntervalHours etc can be used for longer offsets.
00156         time += TTimeIntervalSeconds(20);// 20 secs in future
00157 
00158         TTsTime time2 (time, ETrue);
00159 
00160         iConsole->Printf(KCreateTask);
00161         CreatePersistentScheduleL(scheduleHandle,time2);
00162 
00163         // Create the task to be scheduled
00164         TTaskInfo taskInfo;
00165         
00166         const TInt priority = 2; 
00167         const TInt numberOfRepeats = 2;
00168         // Name of the task
00169         taskInfo.iName = KTaskName;
00170         
00171         // Task priority set by the client. 
00172         // If the client has two tasks with different priorities, 
00173         // the task with the higher priority will be executed first.
00174         taskInfo.iPriority = priority;
00175         
00176         // Task repeats twice
00177         taskInfo.iRepeat = numberOfRepeats;
00178         
00179         _LIT(KScheduleType," persistent schedule");
00180         const TDesC* persistent = &KScheduleType;
00181         HBufC* data = persistent->AllocLC();
00182         
00183         // Add the task
00184         User::LeaveIfError(iScheduler.ScheduleTask(taskInfo, *data, scheduleHandle.iHandle));
00185                                 
00186         // Wait for the entry to fire
00187         iConsole->Printf(KPersistentWait);
00188         const TInt twentySecs = 20000000;
00189         User::After(twentySecs); // pause for 20 seconds
00190         
00191         // Delete all the persistent schedules created
00192         DeleteSchedulesL(scheduleHandle, EAllSchedules);
00193 
00194         CleanupStack::PopAndDestroy(1); // data
00195         
00196         }
00197 
00198         
00213 void CTaskSchedule::CreatePersistentScheduleL(TSchedulerItemRef& aRef, const TTsTime& aStartTime)
00214         {
00215         CArrayFixFlat<TScheduleEntryInfo2>* cSchEntryInfoArray; 
00216         cSchEntryInfoArray = new CArrayFixFlat<TScheduleEntryInfo2>(1);
00217         CleanupStack::PushL(cSchEntryInfoArray);
00218 
00219         // Create an hourly schedule with StartTime of aStartTime
00220         TScheduleEntryInfo2 entry1;
00221         
00222         // Set the first instance when the entry will 
00223         // cause the execution of tasks. 
00224         entry1.SetStartTime(aStartTime);
00225         
00226         // Set the type of interval used between due times 
00227         // for the scheduled entry
00228         entry1.SetIntervalType(TIntervalType(EHourly));
00229         
00230         // Set the period for which the entry is valid. After 8 hours the 
00231         // tasks associated with the entry will not be eligible for execution.
00232         const TInt eightHours = 480; // in minutes 
00233         entry1.SetValidityPeriod(TTimeIntervalMinutes (eightHours));
00234         
00235         // Set the interval between execution of tasks
00236         // Here the interval is 1 hour because the interval type is hourly.
00237         const TInt interval = 1;
00238         entry1.SetInterval(interval);
00239 
00240         cSchEntryInfoArray->AppendL(entry1);
00241         
00242         User::LeaveIfError(iScheduler.CreatePersistentSchedule(aRef, *cSchEntryInfoArray));
00243         CleanupStack::PopAndDestroy(cSchEntryInfoArray);
00244         
00245         }
00246         
00247 
00256 void CTaskSchedule::CreateTransientScheduleL()
00257         {
00258         iConsole->ClearScreen();
00259 
00260         TSchedulerItemRef ref;
00261         CArrayFixFlat<TScheduleEntryInfo2>* cSchEntryInfoArray;
00262         cSchEntryInfoArray = new CArrayFixFlat<TScheduleEntryInfo2>(1);
00263         
00264         CleanupStack::PushL(cSchEntryInfoArray);
00265         ref.iName = KTransientSchedule;
00266         iConsole->Printf(KCreateTransient);
00267         
00268         // Create a schedule entry
00269         TScheduleEntryInfo2 entry;      
00270         TTime now;
00271         
00272         //      Set the date and time of this TTime to the universal time. 
00273         now.UniversalTime();
00274         
00275         // Assign an offset of 15 seconds. TTimeIntervalMinutes, 
00276         // TTimeIntervalHours etc can be used for longer offsets.
00277         TInt offset = 15;
00278         now += TTimeIntervalSeconds(offset);
00279         
00280         // Constructs a TTsTime with a TTime object. 
00281         // ETrue indicates that TTsTime is UTC based time
00282         TTsTime time (now, ETrue);
00283         
00284         // Set the above time as the first time at which 
00285         // the entry will cause execution of tasks. 
00286         entry.SetStartTime(time);
00287         
00288         // Set the type of interval used between due times for scheduled entry
00289         entry.SetIntervalType(TIntervalType(EHourly));
00290         
00291         // Set the period for which the entry is valid. 
00292         // After 2 hours the tasks associated with the entry will not be eligible for execution 
00293         TInt validity = 120;
00294         entry.SetValidityPeriod(TTimeIntervalMinutes (validity));
00295         
00296         // Set the interval between execution of tasks
00297         // Here the interval is 1 hour because the interval type is hourly.
00298         entry.SetInterval(1);
00299         cSchEntryInfoArray->AppendL(entry);
00300         
00301         // Create a transient task to be scheduled
00302         TTaskInfo taskInfo;
00303         // Name of the task
00304         taskInfo.iName = KTransientSchedule;
00305         // Task id
00306         const TInt tId = 0;
00307         taskInfo.iTaskId = tId;
00308         
00309         // The task repeats just once
00310         const TInt numberOfRepeats = 1;
00311         taskInfo.iRepeat = numberOfRepeats;
00312         
00313         // Task priority set by the client. 
00314         // Where a client has two tasks with different priorities, 
00315         // the task with the higher priority will be executed first.
00316         const TInt priority = 2; 
00317         taskInfo.iPriority = priority;
00318         
00319         _LIT(KScheduleType," transient schedule");
00320         const TDesC* transient = &KScheduleType;
00321         HBufC* data = transient->AllocLC();
00322                 
00323         // Schedule the item
00324         User::LeaveIfError(iScheduler.ScheduleTask(taskInfo, *data, ref, *cSchEntryInfoArray));
00325         
00326         // Change the start time and validity duration for the schedule
00327         offset = 19; // 19 seconds in future
00328         now += TTimeIntervalSeconds(offset);
00329         TTsTime newTime (now, ETrue);
00330         entry.SetStartTime(newTime);
00331         validity = 300;
00332         entry.SetValidityPeriod(TTimeIntervalMinutes (validity));
00333         cSchEntryInfoArray->AppendL(entry);
00334         
00335         // Change the transient time based schedule
00336     User::LeaveIfError(iScheduler.EditSchedule(ref.iHandle, *cSchEntryInfoArray));
00337         
00338         CleanupStack::PopAndDestroy(2); // data, CSchEntryInfoArray
00339 
00340         // Check if the tasks scheduled exist
00341         TBool exists;
00342         DoesScheduledItemExistL(ref, exists);
00343         if(!exists)
00344                 {
00345                 User::Leave(KErrNotFound);
00346                 }
00347         // Wait for the task to fire and complete
00348         iConsole->Printf(KTransientWait);
00349         const TInt twentySecs = 20000000;
00350         User::After(twentySecs); // pause for 20 seconds
00351         
00352         iConsole->Printf(KDone);        
00353 
00354         // Transient schedules are deleted automatically once they are executed
00355         // i.e check for count to be zero in the function being called
00356         DoesScheduledItemExistL(ref, exists);
00357         if(exists)
00358                 {
00359                 User::Leave(KErrGeneral);
00360                 }
00361         }
00362 
00369  void CTaskSchedule::DoesScheduledItemExistL(TSchedulerItemRef &aRef, TBool& aExists)
00370         // Extract schedule references from the schedule server based on a filter.
00371         {
00372         aExists = EFalse;
00373         CArrayFixFlat<TSchedulerItemRef>* CSchItemRefArray;
00374         
00375         CSchItemRefArray = new CArrayFixFlat<TSchedulerItemRef>(3);
00376         CleanupStack::PushL(CSchItemRefArray);
00377         
00378         User::LeaveIfError(iScheduler.GetScheduleRefsL(*CSchItemRefArray, EAllSchedules));
00379         
00380         TInt count = CSchItemRefArray->Count();
00381         for(TInt i = 0; i < count; i++)
00382                 {
00383                 // Get a list of schedules created by this executable
00384                 if(aRef.iHandle == (*CSchItemRefArray)[i].iHandle)
00385                         {
00386                         aExists = ETrue;
00387                         iConsole->Printf(KExists);
00388                         iConsole->Printf(KTask, count);
00389                         }
00390                 else
00391                         {
00392                         iConsole->Printf(KOtherTask);
00393                         }
00394                 }
00395 
00396         CleanupStack::PopAndDestroy(); // CSchItemRefArray
00397 
00398         }
00399 
00411 void CTaskSchedule::DeleteSchedulesL(TSchedulerItemRef &aRef, TScheduleFilter aFilter)
00412         {
00413         CArrayFixFlat<TSchedulerItemRef>* CSchItemRefArray;
00414         
00415         CSchItemRefArray = new CArrayFixFlat<TSchedulerItemRef>(3);
00416         CleanupStack::PushL(CSchItemRefArray);
00417         
00418         User::LeaveIfError(iScheduler.GetScheduleRefsL(*CSchItemRefArray, aFilter));
00419         
00420         TInt count = CSchItemRefArray->Count();
00421         iConsole->Printf(KTask, count);
00422         
00423         for(TInt i = 0; i < count; i++)
00424                 {
00425                 // Check if the schedules are created by this exe or
00426                 // some other exe
00427                 if(aRef.iHandle == (*CSchItemRefArray)[i].iHandle)
00428                         {       
00429                         // Delete the tasks scheduled by us (this exe)
00430                         iConsole->Printf(KDeleteAllTasks);
00431                         User::LeaveIfError(iScheduler.DeleteTask(aRef.iHandle));
00432                         // Delete the schedules created by us (this exe)
00433                         iConsole->Printf(KDeleteAllSchedules);
00434                         User::LeaveIfError(iScheduler.DeleteSchedule(aRef.iHandle));
00435                         
00436                         iConsole->Printf(KPressAKey);
00437                         iConsole->Getch();
00438                                         
00439                         }
00440                 else
00441                         {
00442                         // Not deleting the tasks or schedules as,
00443                         // they are not created by this exe
00444                         iConsole->Printf(KOtherTask);
00445                         }
00446                 }
00447         CleanupStack::PopAndDestroy(); // CSchItemRefArray
00448         
00449         }
00450         
00451 void MainL()
00452         {
00453         // Create an Active Scheduler to handle asychronous calls
00454         CActiveScheduler* scheduler = new (ELeave) CActiveScheduler;
00455         CleanupStack::PushL(scheduler);
00456 
00457         // Install the active scheduler
00458         CActiveScheduler::Install( scheduler );
00459         CTaskSchedule* app = CTaskSchedule::NewLC();
00460         
00461         // Connect and register with the task scheduler
00462         app->ConnectAndRegisterL();
00463         
00464         // Create a persistent schedule and add tasks to it
00465         app->PersistentScheduleL();
00466                 
00467         // Create a transient schedule and add tasks to it
00468         app->CreateTransientScheduleL();
00469         
00470         CleanupStack::PopAndDestroy(2); // app, scheduler
00471 
00472         }
00473 
00474 TInt E32Main()
00475         {
00476     __UHEAP_MARK;
00477     CTrapCleanup* cleanup = CTrapCleanup::New();
00478     if(cleanup == NULL)
00479         {
00480         return KErrNoMemory;
00481         }
00482         
00483     TRAPD(err, MainL());
00484         if(err != KErrNone)
00485                 {
00486                 User::Panic(_L("Failed to complete"),err);
00487                 }
00488     delete cleanup;
00489   
00490     __UHEAP_MARKEND;
00491     return KErrNone;
00492         }

Generated by  doxygen 1.6.2