-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathE_task_queue.py
More file actions
193 lines (137 loc) · 3.86 KB
/
E_task_queue.py
File metadata and controls
193 lines (137 loc) · 3.86 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
import dill
import argparse
import os
import tempfile
import time
import fcntl
QUEUE_FILE = "tasks.dat"
RESULT_FILE = "results.log"
# -----------------------------
# Example functions that can be queued
# -----------------------------
def add(a, b):
return a + b
def multiply(a, b):
return a * b
def say_hello(name):
return f"Hello {name}"
FUNCTIONS = {
"add": add,
"multiply": multiply,
"hello": say_hello
}
# -----------------------------
# File locking
# -----------------------------
def lock_file(f):
fcntl.flock(f, fcntl.LOCK_EX)
def unlock_file(f):
fcntl.flock(f, fcntl.LOCK_UN)
# -----------------------------
# Load queue
# -----------------------------
def load_queue():
if not os.path.exists(QUEUE_FILE):
return []
with open(QUEUE_FILE, "rb") as f:
lock_file(f)
try:
data = dill.load(f)
except Exception:
data = []
unlock_file(f)
return data
# -----------------------------
# Save queue safely
# -----------------------------
def save_queue(queue):
with tempfile.NamedTemporaryFile("wb", delete=False) as tmp:
dill.dump(queue, tmp)
temp_name = tmp.name
os.replace(temp_name, QUEUE_FILE)
# -----------------------------
# Add task
# -----------------------------
def add_task(func_name, args, delay=0):
queue = load_queue()
run_at = time.time() + delay
task = {
"function": func_name,
"args": args,
"time": time.time(),
"run_at": run_at
}
queue.append(task)
save_queue(queue)
print("Task added.")
print("Scheduled for:", time.ctime(run_at))
# -----------------------------
# List tasks
# -----------------------------
def list_tasks():
queue = load_queue()
if not queue:
print("No pending tasks.")
return
for i, task in enumerate(queue):
print(f"{i+1}. {task['function']} {task['args']}")
# -----------------------------
# Run next task
# -----------------------------
def run_next():
queue = load_queue()
if not queue:
print("No tasks in queue.")
return
now = time.time()
for i, task in enumerate(queue):
if task["run_at"] <= now:
task_to_run = queue.pop(i)
save_queue(queue)
func = FUNCTIONS.get(task_to_run["function"])
try:
result = func(*task_to_run["args"])
status = "SUCCESS"
except Exception as e:
result = str(e)
status = "FAILED"
with open(RESULT_FILE, "a") as f:
f.write(f"{status} | {task_to_run} | Result: {result}\n")
print("Executed:", task_to_run)
print("Result:", result)
return
print("No tasks are ready to run yet.")
# -----------------------------
# Clear queue
# -----------------------------
def clear_queue():
save_queue([])
print("Queue cleared.")
# -----------------------------
# CLI
# -----------------------------
def main():
parser = argparse.ArgumentParser(description="File-based Task Queue")
sub = parser.add_subparsers(dest="command")
add_cmd = sub.add_parser("add")
add_cmd.add_argument("function")
add_cmd.add_argument("args", nargs="*")
add_cmd.add_argument("--delay", type=int, default=0, help="Delay execution in seconds")
sub.add_parser("list")
sub.add_parser("run")
sub.add_parser("clear")
args = parser.parse_args()
if args.command == "add":
func = args.function
arguments = [eval(x) if x.isdigit() else x for x in args.args]
add_task(func, arguments, args.delay)
elif args.command == "list":
list_tasks()
elif args.command == "run":
run_next()
elif args.command == "clear":
clear_queue()
else:
parser.print_help()
if __name__ == "__main__":
main()