[python 일반] How to Run a Periodic Background Task in Python

You can run a periodic task in the background via a daemon thread.

In this tutorial you will discover how to run a periodic task in the background in Python.

Let’s get started.

Need for a Periodic Background Task

A thread is a thread of execution in a computer program.

Every Python program has at least one thread of execution called the main thread. Both processes and threads are created and managed by the underlying operating system.

Sometimes we may need to create additional threads in our program in order to execute code concurrently.

Python provides the ability to create and manage new threads via the threading module and the threading.Thread class.

You can learn more about Python threads in the guude:

In concurrent programming, we may need to run a task periodically in the background.

This may be for many reasons, such as:

  • Reloading or refreshing data in the application.
  • Storing or saving data from the application.
  • Reporting or logging progress of the application.

Periodically means that the task is repeated after a consistent time interval, such as:

  • Every few seconds.
  • Every few minutes.
  • Every few hours.

Background means that the task is not the main purpose of the application, but instead is a task that supports the main application.

How can we run a periodic task in the background in Python?

Run loops using all CPUs, download your FREE book to learn how.

How to Create a Periodic Background Task

You can run a periodic task in the background using a daemon thread with a while loop and a sleep.

daemon thread is a background thread. Daemon is pronounced “dee-mon“, like the alternate spelling “demon“.

A thread may be configured to be a daemon or not, and most threads in concurrent programming, including the main thread, are non-daemon threads (not background threads) by default. The difference between daemon threads and non-daemon threads is that the process will exit if only daemon threads are running, whereas it cannot exit if at least one non-daemon thread is running.

As such, daemon threads are helpful for executing tasks in the background to support the non-daemon threads in an application.

If you are new to daemon threads, you can learn more about them here:

A Python threading.Thread instance can be configured to be a daemon thread.

We can configure a new thread to be a daemon thread by specifying the “daemon” argument to True in the constructor of the threading.Thread class.

For example:

We can configure a new daemon thread to execute a custom function that will execute a program specific task periodically.

For example we might define a new function named background_task() that takes an integer argument in seconds.

Then configure a new threading.Thread instance to execute this function via the “target” keyword and pass an argument to the function via the “args” argument. The thread can be made daemon via the “daemon” argument and the thread can be given a meaningful name via the “name” argument.

Periodically means repeatedly after the same time interval for as long as the program is running.

This can be achieved with a while-loop that will execute our desired task each interval and sleep for a configured number of seconds.

For example:

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

Because the thread executing our task is a daemon thread, it will not prevent the program from exiting once the tasks of the main thread are finished.

Now that we know how to run a periodic task in the background, let’s look at a worked example.

Example of a Periodic Background Task

We can explore how to run a periodic background task in a daemon thread.

In this example, we will define a new function that will execute our task every few seconds. This new task will be started in the main thread and run in the background while the main thread proceeds with its own tasks.

Firstly, we can define a new function named background_task() that will execute our background task.

The function will take one argument which is the interval in seconds between each execution of the task.

We can then create a while-loop that will run for the duration of the program.

Each iteration of the loop, the function will execute a custom background task and sleep for the configured interval. The order of the task execution and sleep does not matter and may be specific to your application, although a sleep first ensures an initial delay before the first execution of the task.

This may be desirable as it gives the main thread a chance to start running.

In this case, our periodic task will be to simply report a message, but it may be any application specific task you like.

Tying this together, the complete background_task() function for executing our periodic background task is listed below.

Next, we can create a new threading.Thread instance and configure it to execute our background task function.

The name of the function can be specified via the “target” argument and the time interval can be passed via the “args” argument. We can also configure the thread to be a daemon background thread via the “daemon” argument and give the thread a meaningful name via the “name” argument.

We will configure the background task to run (about) every three seconds. We don’t have fine grained control over when the thread will run exactly, but it is close enough.

Once defined, the new background thread can be started.

Next, the main thread can carry on with the normal execution of the program.

We can simulate this with a sleep for ten seconds, allowing the background task to run a few times.

Finally, the main thread will finish its main task (of sleeping), and terminate. This will terminate the application as the background thread is a daemon thread and will be terminated automatically by the process.

Tying this together, the complete example is listed below.

Running the example first creates and starts the daemon thread.

This runs our while-loop in our custom background task function. Each iteration of the loop, the thread will sleep for three seconds then report a message for the life-time of the program.

The main thread then carries on as per normal.

After ten seconds, the main thread wakes up, and terminates, terminating the entire program including the running daemon thread in the background.

Note, daemon threads are terminated abruptly and you may need to pay special attention to the handling of any open resources, like files and socket connections.

 

[출처] https://superfastpython.com/thread-periodic-background/

 

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
87 [python 일반] 파이썬에서 도커 사용하기: 기초부터 배포까지 졸리운_곰 2024.12.01 410
86 [python 일반] 파이썬 디컴파일 방지 난독화 초간단 방법 file 졸리운_곰 2024.08.13 539
85 [python 일반] [Python] python 예제 - 프로그램 실행 위치 확인 방법 3종 - os.getcwd,... 졸리운_곰 2024.07.28 451
84 [python 일반] [Python] How to capture output of Python's interpreter and show in a Text widget? 졸리운_곰 2024.07.26 230
83 [python 일반] [Python] How to Fix Python’s “List Index Out of Range” Error in For Loops 졸리운_곰 2024.07.26 284
82 [python 일반] [Python] Python 리스트에 특정 값이 있는지 체크하기 졸리운_곰 2024.07.26 418
81 [python 일반] [Python] 원하는 시간마다 파이썬 자동 실행 file 졸리운_곰 2024.07.25 337
80 [python 일반] [Python] pyinstaller] PyInstaller -i, --add-data로 아이콘(icon)을 포함하자 file 졸리운_곰 2024.07.19 428
79 [python 일반] [Python] pyinstaller : 파이썬 컴파일 시 코드 암호화 & 복호화 file 졸리운_곰 2024.06.10 374
78 [python 일반] ** Date형식을 String형식으로 변환 ** 졸리운_곰 2024.06.08 297
77 [python 일반] [Python] strftime과 strptime file 졸리운_곰 2024.06.07 377
» [python 일반] How to Run a Periodic Background Task in Python 졸리운_곰 2024.06.07 324
75 [python 일반] *win32ctypes.pywin32.pywintypes.error when using pyinstaller in VS Code - Possible Virus/Trojan? 졸리운_곰 2024.06.07 453
74 [python 일반] 【Python】The 'pathlib' package is an obsolete backport of a standard library ・・・ 졸리운_곰 2024.05.30 318
73 [Python 일반] 파이썬 exe 파일 만들기 졸리운_곰 2024.05.30 307
72 [Python] 클립보드 무엇인가? Pyperclip을 통한 자동화 file 졸리운_곰 2024.05.06 364
71 [Python] PyQt와 PySide에 대한 잡설 file 졸리운_곰 2024.04.25 253
70 [python 일반] How to Update All Python Packages : 설치된 파이썬 패키지 모두 업데이트 하기 file 졸리운_곰 2024.03.16 604
69 [python, C++] Interfacing C++ and Python with the Python API : C++ 및 Python과 Python API의 인터페이스 file 졸리운_곰 2023.08.18 302
68 [python 일반] 파이참 에러 : Fatal Python error: init_stdio_encoding: failed to get the Python codec name of the stdio encoding file 졸리운_곰 2023.07.06 354
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED