How to execute functions at specific seconds every minute in python

I want to execute two functions every minute. After 1.5 seconds Dowork1() and Dowork2() also after 31 seconds execute Dowork2(). Following code is working but it is delaying and blocking other threads as this is continuous while loop. i have thought of using sleep two time but it will be messy and difficult to calculate exact time of sleep. Please let me know what is best way to do this.

dateTimeObj = datetime.now()
minute = dateTimeObj.minute
hour = dateTimeObj.hour
firstExecuteseconds = 1.5
secondExecuteseconds = 31.0
while True:
  if hour < datetime.now().hour:        
     hour = datetime.now().hour
     minute = datetime.now().minute - 1
  if minute < datetime.now().minute:
    isFirstExecuted = False
    isSecondExecuted = False
    if datetime.now().second > firstExecuteseconds and isFirstExecuted == False:
      DoWork1()
      DoWork2()
      isFirstExecuted = True
    if datetime.now().second > secondExecuteseconds and isSecondExecuted == False:
      DoWork2()
      isSecondExecuted = True
    if isFirstExecuted and isSecondExecuted:
      hour = datetime.now().hour
      minute = datetime.now().minute

6

If you want to run a function every one minute without blocking other threads, you can do:

import threading
import time

def my_task():
    print("Task executed at:", time.ctime())

def execute_task_every_minute():
    while True:
        my_task()
        time.sleep(60)  # Wait for 60 seconds before running again

# Create a thread to run the function
thread = threading.Thread(target=execute_task_every_minute)

# Start the thread
thread.start()

So you should make two threads for your functions and do sleeping in those threads which doesn’t block your main thread.

You can also calculate the execution time of you operation and sleep the remaining time to be exact.

1

I think using the asyncio library makes sense since you are writing concurrent processes.

import asyncio

async def task1():
    await asyncio.sleep(1.5)
    print("task1()")

async def task2():
    await asyncio.sleep(31)
    print("task2()")

async def background_task():
    print("Long background task...")
    await asyncio.sleep(600)
    print("...done")

async def schedule_tasks():
    while True:
        start_time = asyncio.get_running_loop().time()
        task1_coroutine = asyncio.create_task(task1())
        task2_coroutine = asyncio.create_task(task2())
        elapsed_time = asyncio.get_running_loop().time() - start_time
        if elapsed_time < 60: 
            await asyncio.sleep(60 - elapsed_time)

async def main():
    asyncio.create_task(background_task())
    await schedule_tasks()

if __name__ == "__main__":
    asyncio.run(main())

Does having multiple synchronous python programs interacting make sense? You might want to learn about cron for starting programs on a schedule in Mac and Linux, or Windows Task Scheduler. Then you need to figure out how to do interprocess communication safely.

One way to do this is to separate the scheduler (your while loop) from the actual work being performed. Instead of performing the functions directly in the while loop, you can spawn new threads for each execution. This frees up the scheduler to continue checking the time and launch new threads with a good degree of precision and not have its timing impacted by waiting for tasks (your functions) to complete.

In a simplified example:

while True:
    if is_time_to_execute_task_1():
        task_thread = threading.Thread(target=DoWork1)
        task_thread.start()
    if is_time_to_execute_task_2():
        task_thread = threading.Thread(target=DoWork2)
        task_thread.start()
    time.sleep(0.01)  # or whatever resolution you need

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật