当我们需要在程序中执行某个重要的操作的时候一般会怎么做?
首先,为了保证它一定会执行成功,大学期间的我肯定会加个循环,再加个延时,让它一直执行直到成功之后退出,类似于这样:
while(set_result)
{
set_result = set_service_state(state, NULL);
if((++Cnt) > 10)
{
break;
}
osDelay(1000);
}
简单粗暴,常规用用似乎也没有什么问题。但是总觉得这样的程序不够优雅,可能在一些老鸟看来甚至有点愚蠢。
这样的程序,在没有使用操作系统开发的时候,可能是比较方便快捷的选择。
然而,在使用操作系统的时候,就应该充分利用操作系统的优点了,否则跟咸鱼有什么区别?
其实,关键思想也很简单,就是利用定时器和消息队列,类似于这样:
osTimerId_t g_sth_to_do_timer = NULL;
void sth_to_do_cb(osTimerId_t xTimer)
{
UNUSED(xTimer);
if(do_sth == OK)
{
}
else
{
send_to_incoming_queue();//执行失败发送到主任务中再执行一次
}
}
void sth_to_to(void)
{
if(NULL == g_sth_to_do_timer)
{
g_sth_to_do_timer = osTimerNew(sth_to_do_cb,osTimerOnce, NULL,NULL);
}
else if(osTimerIsRunning(g_sth_to_do_timer) == 1)
{
osTimerStop(g_sth_to_do_timer);
}
if(osTimerStart(g_sth_to_do_timer, (uint32_t)osMs2Tick((uint64_t)LWM2M_STATE_QUREY_TIMER * 1000)) != osOK)//每次执行的时间间隔
{
APP_COAP_INFO("sth to do failed");
}
}
void main_task( void *unused_p )
{
UNUSED(unused_p);
for(;;)
{
if (osMessageQueueGet(incoming_queue, (void*)&msg, NULL, osWaitForever) == osOK )
{
switch(msg)
{
case 1:
break;
case 2:
break;
case TO_DO_STH:
sth_to_to();//在主任务中注册定时器及回调函数
break;
default:
break;
}
}
}
}
看起来是不是高级一点?
网友评论