增加AddTask,支持成员函数作为任务函数

This commit is contained in:
Stone 2016-06-13 14:18:47 +00:00
parent 137c0df8bc
commit f03e134606
4 changed files with 27 additions and 11 deletions

View File

@ -31,22 +31,26 @@ typedef void (*EventHandler)(void* sender, void* param);
// 传入数据缓冲区地址和长度,如有反馈,仍使用该缓冲区,返回数据长度
typedef uint (*DataHandler)(void* sender, byte* buf, uint size, void* param);
template<typename T, typename TArg>
class Delegate
{
public:
void* Target;
void* Method;
// 构造函数后面的冒号起分割作用,是类给成员变量赋值的方法
// 初始化列表更适用于成员变量的常量const型
Delegate(T* target, void(T::*func)(TArg)) : _Target(target), _Func(func) {}
template<typename T, typename TArg>
Delegate(T* target, void(T::*func)(TArg)) : Target(target), Method(&func) {}
template<typename T, typename TArg>
void Invoke(TArg value)
{
(_Target->*_Func)(value);
}
auto obj = (T*)Target;
typedef void(T::*TAction)(TArg);
auto act = *(TAction*)Method;
private:
T* _Target;
void (T::*_Func)(TArg);
(obj->*act)(value);
}
};
template<typename T, typename TArg, typename TArg2>

View File

@ -115,6 +115,11 @@ public:
public:
// 创建任务返回任务编号。dueTime首次调度时间msperiod调度间隔ms-1表示仅处理一次
uint AddTask(Action func, void* param, int dueTime = 0, int period = 0, cstring name = nullptr) const;
template<typename T>
uint AddTask(void(T::*func)(), T* target, int dueTime = 0, int period = 0, cstring name = nullptr)
{
return AddTask(*(Action*)&func, target, dueTime, period, name);
}
void RemoveTask(uint& taskid) const;
// 设置任务的开关状态同时运行指定任务最近一次调度的时间0表示马上调度
bool SetTask(uint taskid, bool enable, int msNextTime = -1) const;

View File

@ -242,7 +242,8 @@ void TaskScheduler::Start()
if(Running) return;
#if DEBUG
Add(ShowStatus, this, 10000, 30000, "任务状态");
//Add([](void* p){ ((TaskScheduler*)p)->ShowStatus(); }, this, 10000, 30000, "任务状态");
Add(&TaskScheduler::ShowStatus, this, 10000, 30000, "任务状态");
#endif
debug_printf("%s::准备就绪 开始循环处理%d个任务\r\n\r\n", Name, Count);
@ -323,9 +324,10 @@ void TaskScheduler::Execute(uint msMax)
#pragma arm section code
// 显示状态
void TaskScheduler::ShowStatus(void* param)
void TaskScheduler::ShowStatus()
{
auto host = (TaskScheduler*)param;
//auto host = (TaskScheduler*)param;
auto host = this;
debug_printf("Task::ShowStatus [%d] 平均 %dus 最大 %dus 当前 ", host->Times, host->Cost, host->MaxCost);
DateTime::Now().Show();

View File

@ -78,6 +78,11 @@ public:
// 创建任务返回任务编号。dueTime首次调度时间ms-1表示事件型任务period调度间隔ms-1表示仅处理一次
uint Add(Action func, void* param, int dueTime = 0, int period = 0, cstring name = nullptr);
template<typename T>
uint Add(void(T::*func)(), T* target, int dueTime = 0, int period = 0, cstring name = nullptr)
{
return Add(*(Action*)&func, target, dueTime, period, name);
}
void Remove(uint taskid);
void Start();
@ -85,7 +90,7 @@ public:
// 执行一次循环。指定最大可用时间
void Execute(uint msMax);
static void ShowStatus(void* param); // 显示状态
void ShowStatus(); // 显示状态
Task* operator[](int taskid);
};