Python script run every 1 second for 3 hours in a row

Asked

Viewed 271 times

0

I need to run a Python script every 1 second for 3-4 hours a day.

This my script updates the data in a table, performs some calculations and takes an action if the calculation rule determines.

Although simple, I could not find something on the forums that could help me to have a direction.

I’d like some suggestions on how I could do that.

2 answers

2

In my view it has two forms:

  1. Internal loop in the script

You can put your code inside a loop with a timer like this:

import time

while True:
    ... seu script aqui
    time.sleep(1)
  1. You could use the "watch" command from linux to run the command from 1 in 1 seconds, for example:
$ watch -n 1 python meuscript.py
  • I did the test and it worked to run the period. To restrict the hours period, there is some function in this Time library?

  • No, but you can do a simple count of: 3h = 60s * 60m * 3h = 10.800s And then change the loop slightly to "while count < 10800" and at the end of it do "count += 1"

1

#https://pypi.org/project/APScheduler/

Pip install apscheduler

Try scheduled (scheduled scheduling)

from apscheduler.schedulers.background import BackgroundScheduler

 scheduler = BackgroundScheduler()
    scheduler.add_job(train_model, 'interval', hours=3)
    scheduler.start()

If you want to create a medium without api:

import time
import random 

def infinito():
  print("teste")

while True:
    try:
        if infinito() == 1:
            break
    except:
        parada = random.randrange(1, 10)#por um tempo aleatório entre 1-10 ira parar 
        time.sleep(int(parada))
        #time.sleep( parada * 60 )      #a cada minuto ira entrar em um lopp infinito
        pass

no 60 exchange for minutes to hour or days

Browser other questions tagged

You are not signed in. Login or sign up in order to post.