How to sync functions with system's clock

I’m trying to automate a function to delete the content of a text file at a specific hour.
I tried this:

import datetime

contenuto = open(' file.txt ', r+)
ora = datetime.datetime.now()
format_ora = ora.strftime('%H:%M')
ora_stampa = str(format_ora)
if ora_stampa == '00:00':
    contenuto.truncate(0)

but nothing happen and any error raises.

Then, I would make it work in background as daemon or something like that.
Can someone please suggest any solution?

Thanks in advance.

These two lines of code:
format_ora = ora.strftime('%H:%M')
ora_stampa = str(format_ora)

… produce identical string objects.

The 'if: branch will only run at “00:00” and as such will not run until midnight, your local time.

What you’ll need (unless I’m misunderstanding) is a infinite loop that keeps on checking for “00:00”.

That said, I’d simply use the time.sleep function, with the sleep set to the approximate delay until, say, “23:59”, rather than have a loop that will, at most, run for 23 hrs and 59 mins, without doing anything of use: it’s simply consuming CPU clock cycles.

1 Like

It’s not necessary to use Python for this. Just use your operating system’s scheduler.

For example, in systems with cron, put this in your crontab:

* 0 * * * truncate -s 0 file.txt

to clear the file at midnight every day.

2 Likes

In addition to what @rob42 wrote, note that there is no reason to convert the hours and minutes to a string. Just compare the hour and minute to zero, something like:

if ora.hour == ora.minute == 0:
    ...

I would also argue that the logic for executing your code at a specific time belongs outside of it. I don’t know what platform you are using, but on Unix-like systems such as MacOS and Linux, cron is used to schedule take at specific times. That would completely dispense with any need to check the time.

2 Likes

I recommend to use systemd timer units not cron as systemd do timers are easier to read and have powerful features if you need it. You can have timers for you as a non root user or system timers.

This is useful to me because I misunderstood the way the interpreter work in this case. I saw that the only variable ‘ora’ print a long string about ‘day, month, year, hour, second…’, so I was thinking that the interpreter need to ‘understand’ a proper way to read the ‘if’ statement, that’s why I formatted it in that way, just to have an easy formatting at reading (both for the interpreter and for myself). Maybe, it is a little thing, but for me is a way to understand how to get a sort of ‘code’s economy’.

This is exactly what I need. While I was opening this thread, I was thinking about that, but I never automate anything using using the os. For sure, this is the best way and I will choose it for my need. By the way, on my system there isn’t a built-in cron app, so what would be the best choice between fcron, cronie, bcron, anacron, etc, etc?

I’m coding on gnu/linux but the software that I’m writing will runs on windows. So, I need the equivalent command of ‘cron’ for scheduling task. Anyway, I will try with systemd too.

1 Like

https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/schtasks-create

If you want something to run at a specific time, it needs to sleep until that time arrives.

import time
import datetime

filename = "file.txt"
now = datetime.datetime.now()
# calculate timedelta
next_day = now.replace(hour=0, minute=0, second=0, microsecond=0) + datetime.timedelta(days=1)
delta = next_day - now
# wait for next 00:00
time.sleep(delta.total_seconds())
# truncate the file
with open(filename, "wb"):
    pass