File size: 2,341 Bytes
7c4332a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import asyncio
import logging
from fastapi import BackgroundTasks, HTTPException

from concurrent.futures import ThreadPoolExecutor

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)


class Worker: 
    def doing_work(self, task_manager):
        task_manager.task_status["status"] = "Running"
        for i in range(1, 101):
            if task_manager.task_status["status"] == "Stopped":
                break
            asyncio.sleep(1)  # Simulate a time-consuming task
            task_manager.task_status["progress"] = i
            logger.info('process ' + str(i) + '%' + ' done')

        if task_manager.task_status["status"] != "Stopped":
            task_manager.task_status["status"] = "Completed"



class TaskManager:

    task_status = {"progress": 0, "status": "Not started"}
    task = None

    #def __init__(self):

    worker = Worker()

    async def doing_work(self):
        loop = asyncio.get_running_loop()
        with ThreadPoolExecutor() as pool:
            await loop.run_in_executor(pool, self.worker.doing_work, self)
            #self.worker.doing_work(self)    

        # self.task_status["status"] = "Running"
        # for i in range(1, 101):
        #     if self.task_status["status"] == "Stopped":
        #         break
        #     await asyncio.sleep(1)  # Simulate a time-consuming task
        #     self.task_status["progress"] = i
        #     logger.info('process ' + str(i) + '%' + ' done')

        # if self.task_status["status"] != "Stopped":
        #     self.task_status["status"] = "Completed"


    async def start_task(self):
        if self.task is None or self.task.done():
            self.task_status["progress"] = 0
            self.task_status["status"] = "Not started"
            self.task = asyncio.create_task(self.doing_work())
            return {"message": "Task started"}
        else:
            raise HTTPException(status_code=409, detail="Task already running")

    async def get_task_status(self):
        return self.task_status

    async def stop_task(self):
        if self.task is not None and not self.task.done():
            self.task_status["status"] = "Stopped"
            self.task.cancel()
            return {"message": "Task stopped"}
        else:
            raise HTTPException(status_code=409, detail="No task running")