Forums

How can I bring down my CPU usage?

I have an always-on task that needs to run every 5 minutes 9am-9pm Chicago time. Even between those hours, it is mostly waiting for inputs (a user to enter an event in a calendar). After the user enters the event, the "Calendar_2_Text" program runs and sends a text.

Is there any way to bring down my CPU usage? I'm not sure if the scheduler I'm using or the calculation to determine if the current time is between 9am-9pm is eating up the time. Are print statements also eating the CPU time? If it is easier, you have permission to look directly in my always-on tasks.

import schedule
import datetime
import time
import Calendar2Text
import pytz

tz_Chicago = pytz.timezone('America/Chicago')
def is_time_between(begin_time, end_time, check_time):
            if begin_time < end_time:
                return check_time > begin_time and check_time < end_time # doesn't flag end time
            else: # crosses midnight
                return check_time > begin_time or check_time < end_time

def job_time():
    print("I'm working %s" %
          (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')))


def control_job():
    # run between hours 9am - 9pm
    tnowChicago = datetime.datetime.now(tz_Chicago)
    # is time between 9am and 9pm Chicago time
    if is_time_between(datetime.time(9,0), datetime.time(21,0), tnowChicago.time()):
        job_time()
        Calendar2Text.calendar_2_text()


schedule.every(5).minutes.do(control_job)

while True:
    schedule.run_pending()
    time.sleep(1)

Maybe increasing the sleep time in while True would reduce the CPU usage -- I'm not sure how exactly schedule.every(5).minutes.do(control_job) works in the background and how it interacts with schedule.run_pending() which is invoked all the time. Generally the amount of CPU seconds used depends on the processes you run explicitly in your code and the processes started by the libraries you're using. You may use our API to check periodically your CPU usage and compare it to what your code was doing at certain times to get an overview in time.