Marty
Marty

Reputation: 29

How to still execute finally block when the code is stopped through Task Scheduler?

I have this code example:

import time
from datetime import datetime


def log_info(message: str):
    with open('somefile.log', 'a') as file:
        file.write(f'{datetime.now()}: {message}\n')


try:
    log_info('Process started')
    time.sleep(1000)  # to simulate long running...
finally:
    log_info('Process ended')

When I run the code in PyCharm (even in debug mode with breakpoints) or just in console/terminal and after some time I stop the running, the message "Process ended" is still written to the file. This behavior is correct.
However if I create a task in Windows Task Scheduler, I run the task and stop it (through the Task Scheduler), the "Process ended" message is not logged.
How to fix it?

Upvotes: 0

Views: 53

Answers (1)

asultan904
asultan904

Reputation: 189

By stopping your program via Task Scheduler, the Python interpreter is unexpectedly stopping, and cannot reach the finally block. The finally block only applies when your program is able to run without unexpectedly stopping.

Upvotes: 2

Related Questions