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.
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?
3 answers
While the other answers rely on external programs, you can do the same inside python.
Using time.sleep()
If you don't need to do any other tasks during this 10 min.
#!/usr/bin/env python3
import time
def doThisIn10min():
# Replace this with the function you need to do in 10min
# Or call a other program with subprocess
print("doThisIn10min() executed")
#do something here
#We are done, lets execute doThisIn10min() in 10 min
time.sleep(10*60)
doThisIn10min()
If you need to do other tasks, you can spawn a second thread.
#!/usr/bin/env python3
from threading import Thread
import time
def taskWeDoIn10min():
print("taskWeDoIn10min() started")
time.sleep(10*60) #wait 10 min
# Insert here whit the code you want to execute in 10min
print("taskWeDoIn10min() executed")
def doThisInTheMeantime():
# Replace this with the code you want to execute in the meantime
for i in range(50):
time.sleep(10)
print("inside doThisInTheMeantime()")
t = Thread( target=taskWeDoIn10min )
t.start() #Background task to sleep 10 min and then execute <something>
doThisInTheMeantime() #In the mean time, we can do other things
t.join() #Wait till the background task ended
print("All ended")
Yet a other method is to use the sched
module.
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.
If systemd-run
works for you, that is probably the simplest thing you can do here.
Otherwise, you can use os.fork()
from within Python to spawn a child that stays alive after the parent exits.
If someone else is reading this based on the title, but is writing an industrial Python application that doesn't immediately exit, wants to schedule future tasks, and have those tasks be robust across various system events, neither of those solutions is likely to be as robust as using a dedicated service with a name like task scheduler, task queue, or message broker. Celery is a good example.
0 comment threads