FrankBlack78
FrankBlack78

Reputation: 162

Run a Python function in the background

I want to write a small alarm-clock-script in Python 3. I want to make it a CLI-tool with Click so I can pass an alarm time, a start command and a stop command. I don't need help with this itself.

The problem I struggle with is the fact, that when I run my script / commands, the terminal is not available for other commands. So I want to run the program in the background (or another thread?).

Example:

CLI-command 1: define alarm '12:00:00'
CLI-command 2: start alarm

After I set the alarm-time (with define alarm) and started the start-function (which constantly checks if the alarm time is reached) I want to do other stuff in the same terminal. At 12:00:00 the alarm should raise a sound.

As I said, the function works, but while it runs, I am not able to use the same terminal for other things. How can I manage to put this process (checking if the alarm.time is reached) into the background so that I am still be able to use the same terminal for other stuff?

I want to be os-independent (it should run on Windows, Linux and Mac).

Any advise what to read or look into?

Upvotes: 0

Views: 537

Answers (2)

Sam
Sam

Reputation: 46

If you want to achieve this without adding complexity to your code itself, you can just run using the screen command like so:

$ screen -d -m -S alarmclock python your_alarm_clock_script.py

The '-d -m' will start a detached session. The '-S' allows you to name that session.

You can then use:

$ screen -ls
$ screen -r

to view your sessions and resume the alarmclock session respectively.

This is OS independent so long as your OS has Bash installed.

Upvotes: 1

drauedo
drauedo

Reputation: 696

If you want to run a task in the background you can create a process which does the task that you want and then make the system exit it. You can do this by:

import os
import sys
pid = os.fork()
if pid == 0:
        print("Running task")
        sys.exit()
        sleep(10000)
        print("Task ended")
else:
        print("Running another task")



Upvotes: 1

Related Questions