1//
2// Task.cpp
3//
4// Library: Foundation
5// Package: Tasks
6// Module: Tasks
7//
8// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
9// and Contributors.
10//
11// SPDX-License-Identifier: BSL-1.0
12//
13
14
15#include "Poco/Task.h"
16#include "Poco/TaskManager.h"
17#include "Poco/Exception.h"
18
19
20namespace Poco {
21
22
23Task::Task(const std::string& rName):
24 _name(rName),
25 _pOwner(0),
26 _progress(0),
27 _state(TASK_IDLE),
28 _cancelEvent(Event::EVENT_MANUALRESET)
29{
30}
31
32
33Task::~Task()
34{
35}
36
37
38void Task::cancel()
39{
40 _state = TASK_CANCELLING;
41 _cancelEvent.set();
42 if (_pOwner)
43 _pOwner->taskCancelled(this);
44}
45
46
47void Task::reset()
48{
49 _progress = 0.0;
50 _state = TASK_IDLE;
51 _cancelEvent.reset();
52}
53
54
55void Task::run()
56{
57 TaskManager* pOwner = getOwner();
58 if (pOwner)
59 pOwner->taskStarted(this);
60 try
61 {
62 _state = TASK_RUNNING;
63 runTask();
64 }
65 catch (Exception& exc)
66 {
67 if (pOwner)
68 pOwner->taskFailed(this, exc);
69 }
70 catch (std::exception& exc)
71 {
72 if (pOwner)
73 pOwner->taskFailed(this, SystemException(exc.what()));
74 }
75 catch (...)
76 {
77 if (pOwner)
78 pOwner->taskFailed(this, SystemException("unknown exception"));
79 }
80 _state = TASK_FINISHED;
81 if (pOwner)
82 pOwner->taskFinished(this);
83}
84
85
86bool Task::sleep(long milliseconds)
87{
88 return _cancelEvent.tryWait(milliseconds);
89}
90
91
92bool Task::yield()
93{
94 Thread::yield();
95 return isCancelled();
96}
97
98
99void Task::setProgress(float taskProgress)
100{
101 FastMutex::ScopedLock lock(_mutex);
102
103 if (_progress != taskProgress)
104 {
105 _progress = taskProgress;
106 if (_pOwner)
107 _pOwner->taskProgress(this, _progress);
108 }
109}
110
111
112void Task::setOwner(TaskManager* pOwner)
113{
114 FastMutex::ScopedLock lock(_mutex);
115
116 _pOwner = pOwner;
117}
118
119
120void Task::setState(TaskState taskState)
121{
122 _state = taskState;
123}
124
125
126void Task::postNotification(Notification* pNf)
127{
128 poco_check_ptr (pNf);
129
130 FastMutex::ScopedLock lock(_mutex);
131
132 if (_pOwner)
133 {
134 _pOwner->postNotification(pNf);
135 }
136}
137
138
139} // namespace Poco
140