0

On macOS, I am running a Python script in the background using the package schedule to perform a task every ten seconds, which is just logging the current time. I leave it for several hours for testing but it always "skips" many intervals, sometimes for up to 20 minutes before coming back. What could be causing it?

Here's the code of scheduling.py:

from schedule import every, repeat, run_pending
import datetime
import time
import logging

logging.basicConfig(filename='scheduling.log',
                    format='%(levelname)s: %(message)s',
                    encoding='utf-8', level=logging.DEBUG)

PERIOD = 10
END = datetime.datetime(2023, 4, 9, 11, 55, 0)


@repeat(every(PERIOD).seconds.until(END))
def log():
    logging.info(str(datetime.datetime.now()))


while datetime.datetime.now() < END:
    run_pending()
    time.sleep(1)

I run it with:

python scheduling.py &

If I'm "looking at it," it works well. But this happened overnight:

DEBUG: Running job Job(interval=10, unit=seconds, do=log, args=(), kwargs={})
INFO: 2023-04-09 02:46:11.879731
DEBUG: Running job Job(interval=10, unit=seconds, do=log, args=(), kwargs={})
INFO: 2023-04-09 02:46:21.946566
DEBUG: Running job Job(interval=10, unit=seconds, do=log, args=(), kwargs={})
INFO: 2023-04-09 02:46:32.003987
DEBUG: Running job Job(interval=10, unit=seconds, do=log, args=(), kwargs={})
INFO: 2023-04-09 03:01:56.877848
DEBUG: Running job Job(interval=10, unit=seconds, do=log, args=(), kwargs={})
INFO: 2023-04-09 03:02:06.895503
DEBUG: Running job Job(interval=10, unit=seconds, do=log, args=(), kwargs={})
INFO: 2023-04-09 03:02:16.969738

It went from 2:46 am to 3:01 am, and then later it skipped from 3:04 am to 3:20 am, etc.

I also tried this scheduling using time.sleep(10) and the Timer function of the threading package. They all performed well in the sense that they, at first, do the task at the requested frequency, but when I leave it overnight they fail.

Failures seem to be random (it's not just like they stop when the computer goes to sleep mode until the next morning, unless the sleep mode in fact goes on and off repeatedly).

In a short test I put the computer on sleep mode and it skipped some intervals.

If the problem is the sleep mode, what could I do to avoid it?

1 Answers1

1

Unfortunately while your computer enters sleep mode all programs are paused (https://kingstoncollege.org/do-programs-still-run-when-the-computer-is-in-sleep-mode/). I think the best way out will be to suspend sleeping mode (power options on your computer).

Matmozaur
  • 283
  • 2
  • 6