62 lines
1.5 KiB
C++
62 lines
1.5 KiB
C++
/*
|
|
*******************************************************************************
|
|
* INCLUDE
|
|
*******************************************************************************
|
|
*/
|
|
#include "Task.h"
|
|
#include "Logger.h"
|
|
|
|
namespace Util
|
|
{
|
|
/*
|
|
*******************************************************************************
|
|
* CLASS DEFINE
|
|
*******************************************************************************
|
|
*/
|
|
Task::Task(const std::string& name): _name(name)
|
|
{
|
|
}
|
|
|
|
void Task::run(std::function<void(std::atomic<bool>& isCancelled)> func)
|
|
{
|
|
cancel();
|
|
|
|
Poco::FastMutex::ScopedLock lock(_lock);
|
|
_pThread = new Poco::Thread();
|
|
_isCancelled = false;
|
|
|
|
_pThread->startFunc(
|
|
[this, func]() -> void
|
|
{
|
|
try
|
|
{
|
|
func(_isCancelled);
|
|
}
|
|
catch (Poco::Exception& e)
|
|
{
|
|
logger().error("Task(%s): %s", name(), e.displayText());
|
|
}
|
|
catch (std::exception& e)
|
|
{
|
|
logger().error("Task(%s): %s", name(), std::string(e.what()));
|
|
}
|
|
});
|
|
}
|
|
|
|
void Task::cancel()
|
|
{
|
|
if (isRunning())
|
|
{
|
|
Poco::FastMutex::ScopedLock lock(_lock);
|
|
_isCancelled = true;
|
|
_pThread->join();
|
|
_pThread.reset();
|
|
}
|
|
}
|
|
|
|
bool Task::isRunning()
|
|
{
|
|
Poco::FastMutex::ScopedLock lock(_lock);
|
|
return !_pThread.isNull() && _pThread->isRunning();
|
|
}
|
|
}
|