cocos2dx 定时执行任务

来源:互联网 发布:vscode js格式化插件 编辑:程序博客网 时间:2024/06/03 18:28
主要分为3种: 每帧执行, 每间隔多少时间执行, 只执行一次

1. 每帧执行

  调用scheduleUpdate()方法, 每帧都会回调 update(float time) 方法,调用unscheduleUpdate()停止执行;
如:
bool TestLayer::init()
{
   //编写代码~~~
   this->scheduleUpdate(); 
   return true;
}
void TestLayer::update(float dt){
   Log("每帧都执行~");
}
void TestLayer::onExit()
{
this->unscheduleUpdate();
}

2. 每间隔多少时间执行
   调用schedule(SEL_SCHEDULE selector, float interval)方法, 每间隔interval时间就会执行一次回调方法,
   调用unschedule(SEL_SCHEDULE selector)方法停止执行;   
如:
bool TestLayer::init()
{
   //编写代码~~~
   this->schedule(schedule_selector(TestLayer::updateSelf), 1f);
   return true;
}
void TestLayer::updateSelf(float dt){
   Log("每间隔1秒执行一次~");
}
void TestLayer::onExit()
{
   this->unschedule(schedule_selector(TestLayer::updateSelf));
}

3. 只执行一次
   调用scheduleOnce(SEL_SCHEDULE selector, float delay)方法,延迟delay秒后开始执行一次回调方法,
   调用unschedule(SEL_SCHEDULE selector)方法停止执行;  
如:
bool TestLayer::init()
{
  //编写代码~~~
   this->scheduleOnce(schedule_selector(TestLayer::loadRes),0.1f);
   return true;
}
void TestLayer::loadRes(float dt){
   Log("延迟0.1秒后开始加载资源~");
}
void TestLayer::onExit()
{
   this->unschedule(schedule_selector(TestLayer::loadRes));
}
 
 
 PS:unscheduleAllSelectors()方法停止所有定时任务;
0 0
原创粉丝点击