30
Séquenceur de tâches
- typedef list scheduler;
- extern scheduler scheduler_new( void );
- extern void scheduler_free( scheduler this );
- extern task scheduler_addtask( scheduler this, task atask );
- extern task scheduler_rmtask( scheduler this, task atask );
- extern task scheduler_findtask( scheduler this, char *name, void (*job)( void * ), void *arg );
- extern time_t scheduler_run( scheduler this );
- extern time_t scheduler_nexttime( scheduler this );
- scheduler scheduler_alloc( ) {
- return list_alloc( );
- }
- scheduler scheduler_init( scheduler this ) {
- return this;
- }
- scheduler scheduler_new( void ) {
- return scheduler_init( scheduler_alloc() );
- }
- void scheduler_free( scheduler this ) {
- list_free( this );
- }
- task scheduler_addtask( scheduler this, task atask ) {
- int i, len = list_length( this );
- task tk;
- ONDEBUG2( printf( "[SchedulerAddTask]\n" ));
- for ( i = 0; i < len; i++ ) {
- tk = (task)list_get( this, i );
- if ( tk->attime > atask->attime )
- break;
- }
- ONDEBUG2( printf( "[%s<%i>]\n", atask->name, i ));
- task_setstatus( atask, TASKQUEUED );
- return (task)list_insert( this, i, atask );
- }
- task scheduler_rmtask( scheduler this, task atask ) {
- int i, len = list_length( this );
- task tk;
- ONDEBUG2( printf( "[SchedulerRemoveTask]\n" ));
- for ( i = 0; i < len; i++ ) {
- tk = (task)list_get( this, i );
- if ( tk == atask )
- break;
- }
- ONDEBUG2( printf( "[%s<%i>]\n", atask->name, i ));
- task_setstatus( atask, TASKIDLE );
- return (task)list_delete( this, i );
- }
- task scheduler_findtask( scheduler this, char *name, void (*job)( void * ), void *arg ) {
- int i, len = list_length( this );
- task tk;
- for ( i = 0; i < len; i++ ) {
- tk = (task)list_get( this, i );
- if ( name && strcmp( tk->name, name ) != 0 )
- continue;
- if ( job && tk->job != job )
- continue;
- if ( arg && tk->arg != arg )
- continue;
- return tk;
- }
- return 0;
- }
- time_t scheduler_run( scheduler this ) {
- time_t now = time( 0 );
- task tk;
- ONDEBUG2( printf( "[SchedulerRun]\n" ));
- while ( (tk = (task)list_get( this, 0 )) ) {
- if ( tk->attime > now )
- break;
- ONDEBUG2( printf( "[%s]\n", tk->name ));
- /* remove task from queue before it is run */
- list_delete( this, 0 );
- task_setstatus( tk, TASKRUNNING );
- task_exec( tk );
- task_setstatus( tk, TASKIDLE );
- /* again? */
- if ( tk->period && (!tk->count || --tk->count > 0) ) {
- tk->attime += tk->period; /* next time */
- scheduler_addtask( this, tk );
- }
- }
- return scheduler_nexttime( this );
- }
- time_t scheduler_nexttime( scheduler this ) {
- task tk = list_get( this, 0 );
- return tk ? tk->attime : 0;
- }
Commentaires