-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
375 lines (310 loc) · 10.5 KB
/
main.py
File metadata and controls
375 lines (310 loc) · 10.5 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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
#!/usr/bin/env python3
import argparse
import signal
import sys
import time
from bot_commander import BotManager
from src.scheduler import TaskScheduler
from src.logger import Logger, setup_bot_library_logging
from src.cli_output import CliOutput
from src.config import Config
from src.constants import Bot, Paths
from src.formatters import format_task_list, parse_interval
from src.bot.command_processor import TaskCommandProcessor
from src.bot_health import BotHealthMonitor
from src.commands import (
handle_list,
handle_history,
handle_delete,
handle_set_start_time,
handle_set_interval,
handle_set_arguments,
handle_rename,
handle_copy_task,
handle_edit,
handle_add,
handle_script,
handle_run_id,
handle_ftp_sync,
handle_uv_command,
)
def _interval_arg(value: str) -> int:
"""Argparse adapter for parse_interval that surfaces friendly errors."""
try:
return parse_interval(value)
except ValueError as exc:
raise argparse.ArgumentTypeError(str(exc)) from exc
def parse_arguments() -> argparse.Namespace:
"""Parse command line arguments."""
parser = argparse.ArgumentParser(
description="Task Scheduler for Python Scripts and Batch Files",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
# Add a new task with arguments (use -- to separate scheduler args from script args)
python main.py --script "script.py" --name "task" --interval 5 -- --source "path with spaces" --target "another path"
^^ Everything after this is passed to the script
# Add a task using relative path
python main.py --script "script.py" --name "local script" --interval 1
# Add a batch file task
python main.py --script "backup.bat" --name "backup task" --interval 60
# Intervals can use suffixes m/h/d/w (e.g. 4h, 7d, 1w)
python main.py --script "weekly.py" --name "weekly job" --interval 7d
# Add a uv command task with arguments
python main.py --uv-command "D:\\project" "sync-to-local" --name "Sync" --interval 5 -- --config "config.json"
# Add a task interactively
python main.py --add
# Edit a task interactively
python main.py --edit 1
# List and run existing tasks
python main.py
# Change logging settings
python main.py --log-level DEBUG --detailed-logs true
Note:
- Python scripts should have their own venv in their directory.
- Batch files will run from their own directory.
"""
)
group = parser.add_mutually_exclusive_group()
group.add_argument(
"--add",
action="store_true",
help="Interactive mode to add a new task"
)
group.add_argument(
"--edit",
type=int,
metavar="ID",
help="Edit a task by its ID"
)
group.add_argument(
"--script",
type=str,
help="Path to the Python script or batch file to schedule"
)
group.add_argument(
"--uv-command",
nargs=2,
metavar=("PROJECT_DIR", "COMMAND"),
help="Add a uv command task: PROJECT_DIR is the uv project path, COMMAND is the uv command to run"
)
parser.add_argument(
"--name",
type=str,
help="Descriptive name for the task"
)
parser.add_argument(
"--interval",
type=_interval_arg,
metavar="INTERVAL",
help=(
"Interval between executions: bare minutes (e.g. 5) or with "
"suffix Nm/Nh/Nd/Nw (e.g. 4h, 7d, 1w). Use 0 for manual only."
),
)
parser.add_argument(
"--start-time",
type=str,
metavar="HH:MM",
help="Optional start time for aligned scheduling (e.g., 09:00)"
)
parser.add_argument(
"--set-start-time",
nargs=2,
metavar=("ID", "TIME"),
help="Set or clear start time for a task (use 'none' to clear)"
)
parser.add_argument(
"--set-interval",
nargs=2,
metavar=("ID", "INTERVAL"),
help="Set interval for a task (e.g. 5, 4h, 7d, 1w; 0 = manual only)"
)
parser.add_argument(
"--set-arguments",
type=int,
metavar="ID",
help="Set arguments for a task interactively"
)
parser.add_argument(
"--rename",
type=int,
metavar="ID",
help="Rename a task by its ID (prompts for new name)"
)
parser.add_argument(
"--copy-task",
type=int,
metavar="ID",
help="Copy a task by its ID (creates a duplicate with ' (copy)' suffix)"
)
parser.add_argument(
"--list",
nargs='?',
const='',
default=None,
metavar="FILTER",
help="List scheduled tasks and exit (optional name filter)"
)
parser.add_argument(
"--history",
type=int,
nargs='?',
const=10,
metavar="N",
help="Show the last N task executions (default: 10)"
)
parser.add_argument(
"--delete",
type=int,
metavar="ID",
help="Delete a task by its database ID"
)
parser.add_argument(
"--log-level",
choices=['DEBUG', 'INFO', 'WARNING', 'ERROR'],
help="Set the logging level"
)
parser.add_argument(
"--detailed-logs",
type=str,
choices=['true', 'false'],
help="Enable or disable detailed argument logging"
)
parser.add_argument(
"--run_id",
type=int,
metavar="ID",
help="Run a specific task by its database ID"
)
parser.add_argument(
"--launch-new-process",
action="store_true",
help="Launch task in a new console window (only for manual tasks with interval 0)"
)
parser.add_argument(
"--ftp-sync",
action="store_true",
help="Manually trigger FTP sync of the status page"
)
# Collect remaining arguments after --
parser.add_argument(
'script_args',
nargs=argparse.REMAINDER,
help="Arguments to pass to the script (everything after --)"
)
return parser.parse_args()
def signal_handler(signum, frame):
"""Handle shutdown signals."""
logger.info("Shutdown signal received")
bot_manager.shutdown()
scheduler.shutdown()
sys.exit(0)
if __name__ == "__main__":
try:
# Parse arguments
args = parse_arguments()
# Update logging configuration if specified
config = Config()
if args.log_level:
config.set_logging_level(args.log_level)
if args.detailed_logs:
config.set_detailed_logging(args.detailed_logs.lower() == 'true')
# Initialize logger and scheduler
logger = Logger("Main")
cli = CliOutput()
scheduler = TaskScheduler()
if args.list is not None:
handle_list(scheduler, cli, args.list)
sys.exit(0)
elif args.history is not None:
handle_history(scheduler, cli, args.history)
sys.exit(0)
elif args.delete is not None:
handle_delete(scheduler, cli, args.delete)
sys.exit(0)
elif args.set_start_time:
task_id_str, time_value = args.set_start_time
handle_set_start_time(scheduler, cli, task_id_str, time_value)
sys.exit(0)
elif args.set_interval:
task_id_str, interval_str = args.set_interval
handle_set_interval(scheduler, cli, task_id_str, interval_str)
sys.exit(0)
elif args.set_arguments is not None:
handle_set_arguments(scheduler, cli, args.set_arguments)
sys.exit(0)
elif args.rename is not None:
handle_rename(scheduler, cli, args.rename)
sys.exit(0)
elif args.copy_task is not None:
handle_copy_task(scheduler, cli, args.copy_task)
sys.exit(0)
elif args.edit is not None:
handle_edit(scheduler, cli, args.edit)
sys.exit(0)
elif args.add:
handle_add(scheduler, cli)
sys.exit(0)
elif args.script:
handle_script(scheduler, cli, args)
sys.exit(0)
elif args.uv_command:
handle_uv_command(scheduler, cli, args)
sys.exit(0)
elif args.run_id:
handle_run_id(scheduler, cli, args.run_id)
sys.exit(0)
elif args.ftp_sync:
handle_ftp_sync(cli, config)
sys.exit(0)
# If no specific action was requested, run the scheduler
bot_logger = Logger("Bot", log_file_prefix=Paths.LOG_FILE_PREFIX_BOT)
setup_bot_library_logging()
bot_config_dto = config.get_bot_config()
processor = TaskCommandProcessor(scheduler, bot_config_dto)
bot_manager = BotManager(
message_handler=processor,
config_provider=config,
bot_type=config.get_bot_type(),
)
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
scheduler.start()
# Initialize bot if configured
health_monitor = None
try:
bot_started = bot_manager.start()
if bot_started:
processor.set_notifier(bot_manager.send_message)
bot_logger.info("Bot integration started")
health_monitor = BotHealthMonitor(bot_manager, bot_logger)
except Exception as e:
bot_logger.error(f"Bot failed to start: {e}", exc_info=True)
tasks = scheduler.list_tasks()
logger.info("Current tasks:" + format_task_list(tasks, show_next_run=True))
logger.info("\nPress Ctrl+C to exit")
try:
last_health_check = time.time()
while True:
time.sleep(1)
now = time.time()
if (
health_monitor is not None
and now - last_health_check >= Bot.HEALTH_CHECK_INTERVAL_SECONDS
):
health_monitor.check_health()
last_health_check = now
except KeyboardInterrupt:
logger.info("Keyboard interrupt received")
bot_logger.info("Bot shutting down")
bot_manager.shutdown()
scheduler.shutdown()
sys.exit(0)
except Exception as e:
print(f"Error: {e}", file=sys.stderr)
if "cli" in dir():
cli.error(f"Error: {e}")
elif "logger" in dir():
logger.error(f"Error: {str(e)}", exc_info=True)
sys.exit(1)