Search code examples
pythonpython-3.xmultithreadingpython-multithreadingbackground-process

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?


Solution

  • 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")