两个选择:滚动拥有或使用库:
展示自己拥有的示例代码:
typedef void (*action_func)(void) ;
void action_a(void) {
}
void action_b(void) {
}
truct {
int id ;
action_func f ;
} action_table[] = {
{ 1,action_a },{ 2,action_b }
} ;
int action (int counter)
{
int n_actions = sizeof(action_table)/sizeof(action_table[0]) ;
for (int i=0 ; i <n_actions ; i++ ) {
if ( counter == action_table[i].id ) {
action_table[i].f() ;
break ;
} ;
}
return seconds_elapsed ;
}
添加/更改动作需要更新表。您可以在表格中添加附加属性以更改状态等。
更新1-基于C的cron /事件库
重量轻:
https://
一般用途-可能过大了
,
我接受这种设计。
将代码分为两种功能以使代码可读-一种功能基于计数器进行决策,第二种功能只是基本处理程序。
#include <stdio.h>
typedef int (*scheduler)(int);
typedef void (*worker)(void);
typedef struct event {
scheduler is_it_time_to_run_task;
worker task_handle;
} event_t;
int every_five_seconds(int ticks){
return (ticks % 5) == 0;
}
int every_hour(int ticks){
return (ticks % 3600) == 0;
}
void sound_the_bell(){
printf("bell\n");
}
void do_some_check(){
printf("check\n");
}
int z=0;
int get_counter_from_device(){
return ++z;
}
int main(){
event_t events[]={
{every_hour,sound_the_bell},{every_five_seconds,do_some_check},{NULL,NULL}
};
while(1){ //read some value from device
int counter = get_counter_from_device();
printf("counter: %d\n",counter);
for(event_t *event=events;event->is_it_time_to_run_task;event++){
if(event->is_it_time_to_run_task(counter)){
event->task_handle();
}
}
}
return 0;
}
本文链接:https://www.f2er.com/2995753.html