Question:
A Code Golf Question
I made a console program to show the times, but they are different times from what we know – and it involves a very simple account.
It checks the system time, and when it finds that a minute has passed, it prints the current calculated time on the screen.
Examples of his output:
35.5787037037037
35.69444444444444
36.388888888888886
However, I would like it to work a little better:
I wish it had the precision of a second, or a .beat
For that, I should be able to create a task linked to the system clock, so that it would notify me precisely at the time I determined .
I know it's possible to loop infinitely, and check the system time thousands of times – but I don't really like the idea. The ideal would be to have a listener that lets me know that it's time to perform my task.
It is possible? How to make? (Is there any voodoo magic that allows this?)
- I would like simple examples, in different languages
- console program
- No need to implement the .beat account
- The idea is to free up the program to do other things and have the task started at a precise moment in time.
- One language per answer!
The account, for those who are curious, is this:
(UTC+1segundos + (UTC+1minutos * 60) + (UTC+1horas * 3600)) / 86.4
Answer:
Python
In Python there is a sched
package that can be used to schedule tasks at certain points of time. See the example:
import sched, time, threading, sys
trigger = time.mktime((2017, 6, 14, 21, 15, 36, 0, 0, 0))
def task(trigger):
sys.stdout.write("Tarefa executada com um erro de " + str(time.time() - trigger) + ' segundos\n')
s = sched.scheduler(time.time, time.sleep)
s.enterabs(trigger, 1, task, argument=(trigger,))
t = threading.Thread(target=s.run)
t.start()
while t.is_alive(): pass # Simula o programa executando normalmente
For the example above, the task
function will be executed exactly on 2017-06-14 at 21:15:36, displaying on the screen the message (for example):
Tarefa executada com um erro de 0.0057599544525146484 segundos
Veja funcionando no Repl.it
Referência das funções utilizadas:
sched.scheduler
sched.scheduler.enterabs
sched.scheduler.run
time.mktime
time.time
time.sleep
threading.Thread
threading.Thread.start
threading.Thread.is_alive