Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Comments on How can I schedule a later task in Python?
Parent
How can I schedule a later task in Python?
I want my CLI Python program to schedule a task, and then exit. After some times has passed (say 10 minutes) the task should execute.
The task can be a Python method or a shell command, whatever is easier. I can convert my use case to accommodate it.
This would be on Linux only.
How can I schedule a future task from Python?
Post
Use at
to schedule the command, using subprocess
from Python to invoke at
. It doesn't even require shell=True
. For example:
import shlex, subprocess
subprocess.run(
# `at` command to run now
shlex.split("at now +10 minutes"),
# shell command that `at` will schedule, provided to `at`'s stdin
input="python -m this > this.txt",
# open stdin in text mode with the default encoding
text=True
)
The at
program will detach itself from the terminal, so capturing stdout or stderr from the scheduled task will require a workaround (such as invoking xterm
, or tee
ing to a TTY that will be open when the task runs).
However, if local mail services are available, and at
is run from a su
shell, it will send local mail with the output when the job is completed. Check the man page for details.
0 comment threads