#include "timer.h"
TASK task[TASK_MAX]; //任务数组
int taskcnt = 0; //当前任务数量
void job_1(void)
{
printf("***job_1 over***\n");
}
void new_run(void)
{
int ret,min,i;
ret = search(-1,WAITTING);
min = ret;
if(taskcnt >= 1)
{
for(i=0;i<TASK_MAX;i++)
if(WAITTING == task[i].flag)
if(task[min].xsec > task[i].xsec)
min = i;
task[min].flag = RUNNING;
alarm(task[min].xsec);
}
//还缺少相等情况
}
void do_job(int s)
{
int i,ret,min;
for(i=0;i<TASK_MAX;i++)
{
if(RUNNING == task[i].flag)
{
task[i].job();
task[i].flag = COMPLETED;
ret = i;
}
}
taskcnt--;
regeneration_time(task[ret].xsec); //更新
new_run();
}
int search(int taskid,int flag)
{
int i;
if(flag >= 0)
{
for(i=0;i<TASK_MAX;i++)
if(task[i].flag == flag)
return i;
}
if(taskid >= 0)
{
for(i=0;i<TASK_MAX;i++)
if(task[i].taskid == taskid)
return i;
}
}
void regeneration_time(int base)
{
int i;
for(i=0;i<TASK_MAX;i++)
{
if(task[i].flag == WAITTING)
task[i].xsec = task[i].xsec - base;
}
}
int find_and_store(jobFunc job, int expire)
{
int ret,ret2;
ret = search(-1,COMPLETED);
task[ret].taskid = ret;
task[ret].xsec = expire;
task[ret].job = job;
task[ret].flag = WAITTING;
ret2 = search(-1,RUNNING);
if(expire < task[ret2].xsec)
{
//缺少对同为running状态的改变
task[ret2].flag = WAITTING;
task[ret].flag = RUNNING;
alarm(expire);
}
else if(expire == task[ret2].xsec)
{
task[ret].flag = RUNNING;
alarm(expire);
}
else
alarm(task[ret2].xsec);
return 0;
}
int add_job(void)
{
int ret,lsec,base,jobnum;
int taskid,expire;
jobFunc job=job_1;
printf("in put time:\n");
scanf("%d",&expire);
getchar();
if(taskcnt==0)
{
task[0].taskid = 0;
task[0].xsec = expire;
task[0].job = job;
task[0].flag = RUNNING;
alarm(expire);
}
else
{
ret = search(-1,RUNNING); //排在第一位任务的位置
lsec = alarm(0); //剩余alarm时间
base = task[ret].xsec - lsec; //已过的时间
task[ret].xsec = lsec;
regeneration_time(base);
find_and_store(job,expire);
}
taskcnt++;
return 0;
}
void print(void)
{
int i;
for(i=0;i<TASK_MAX;i++)
if((task[i].flag == WAITTING)||(task[i].flag == RUNNING))
printf("taskid:%d\n",task[i].taskid);
}
int del_job(void)
{
int id,lsec,base,ret;
char inc[10];
printf("input the taskid:\n");
fgets(inc,10,stdin);
ret = strlen(inc);
inc[ret-1] = '\0';
id = atoi(inc);
if(task[id].flag == RUNNING)
{
task[id].flag = COMPLETED;
lsec = alarm(0);
base = task[id].xsec - lsec;
regeneration_time(base);
new_run();
}
else
task[id].flag = COMPLETED;
taskcnt--;
return 0;
}
void print_menu(void)
{
printf("1.add\t2.del\t3.show\n");
}
int main(void)
{
char inc[10];
signal(SIGALRM, do_job);
bzero(task,sizeof(TASK)*TASK_MAX);
while(1)
{
print_menu();
fgets(inc,10,stdin);
switch(inc[0])
{
case '1':add_job();break;
case '2':del_job();break;
case '3':print();break;
default :break;
}
}
return 0;
}
|