Set up scripts to run at regular time intervals without interruption

I am currently working on developing a scheduler that can activate multiple scripts based on specific time intervals. In this case, I have scripts labeled as A, B, and C that need to be triggered at different frequencies - A every minute, B every two minutes, and C every three minutes. Right now, my goal is to simply display these triggers on screen.

I attempted to use the Python Sched module for this task but encountered some issues with the functionality of the triggers. After making modifications, the scheduler either runs continuously without executing the correct scripts or triggers all three scripts only once before exiting unexpectedly.

Here is an example of code triggering the scripts only once:

import sched, time
from datetime import datetime

s = sched.scheduler(time.time, time.sleep)
def print_time(a='default'):
    print("From print_time", datetime.now().strftime("%H%M%S"), a)

def print_some_times():
    print("Start time :" + datetime.now().strftime("%H%M%S"))
    s.enter(18, 1, print_time, kwargs={'a': '3 Minutes Trigger'})
    s.enter(12, 1, print_time, kwargs={'a': '2 Minutes Trigger'})
    s.enter(6, 1, print_time, kwargs={'a': '1 Minute Trigger'})
    s.run()
    print("End time :" + datetime.now().strftime("%H%M%S"))

print_some_times()

And below is an example of code that triggers continuously but inaccurately:

import sched, time
from datetime import datetime

s = sched.scheduler(time.time, time.sleep)
def print_time(a='default'): 
    s.enter(5, 1, print_time, ())  
    print("From print_time " + datetime.now().strftime("%H%M%S") + a)

def print_some_times():
    print("Start time :" + datetime.now().strftime("%H%M%S"))
    s.enter(18, 1, print_time, kwargs={'a': ' 3 Minutes Trigger'})
    s.enter(12, 1, print_time, kwargs={'a': ' 2 Minutes Trigger'})
    s.enter(6, 1, print_time, kwargs={'a': ' 1 Minute Trigger'})      
    s.run()
    print("End time :" + datetime.now().strftime("%H%M%S"))

print_some_times()

Please note that I have adjusted the timing values in the code samples to speed up the output generation process.

The actual result from running the first code snippet:
Start time :163945
From print_time 163951 1 Minute Trigger
From print_time 163957 2 Minutes Trigger
From print_time 164003 3 Minutes Trigger
End time :164003

Expected output:
The trigger set for 1-minute intervals should fire every one minute
The trigger set for 2-minute intervals should fire every two minutes, and so forth.

Answer №1

the schedule module is not meant for this purpose.

you may want to consider using this scheduling library instead.

installation can be done with python3 -m pip install schedule

import schedule
import time
from datetime import datetime


def print_time(a='default'):
    print("Current Time: " + datetime.now().strftime("%H%M%S") + a)


def print_some_times():
    print("Start time :" + datetime.now().strftime("%H%M%S"))
    schedule.every(3).minutes.do(print_time, a='  3 Minutes Trigger')
    schedule.every(2).minutes.do(print_time, a='  2 Minutes Trigger')
    schedule.every(1).minutes.do(print_time, a='  1 Minute Trigger')
    schedule.every(1).minutes.do(print_time, a='  1 Minute Trigger')
    print("End time :" + datetime.now().strftime("%H%M%S"))


print_some_times()

while True:
    schedule.run_pending()
    time.sleep(1)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring binary search tree traversal made simple on LeetCode platform

Suppose you have the root node of a binary search tree (BST) along with a specific value. Your task is to locate the node in the BST that has a value equal to the given one. Return the subtree rooted at that node. If no such node exists, then you should re ...

Changing dictionary rows into individual columns in pandas dataframes

I am working with a dataframe that has two columns. One of these columns contains dictionaries with multiple keys and values. My goal is to expand these dictionary keys into separate columns using pandas. Is there a way to achieve this? In [1]:print df Ou ...

Executing a script for every row in a table using Python and Selenium

As a newcomer to Python and Selenium, I have been struggling with a specific task for days now. Despite my efforts to search and experiment, I find myself completely stuck. My goal is to access sales records within a table that contains information about ...

Python script experiencing empty file during execution with sequential write actions

Recently, I created a simple script to write some lines to a file: f = open('file.txt','w') while(operator): f.write("string") f.close() However, I noticed that while the script is running, the file remains empty. Only after th ...

Import data in pipe-separated CSV format into Hive

Having trouble loading a pipe separated CSV file into a Hive table using Python. Can anyone provide some guidance? Here is the full code snippet: from pyhive import hive host_name = "192.168.220.135" port = 10000 user = "cloudera" password = "clouder ...

Switching images dynamically using Flask and JavaScript

I'm currently working on Flask and encountering a perplexing issue. I'm attempting to update an image using JavaScript, but I am getting these errors from Flask: ... 12:05:34] "GET / HTTP/1.1" 200 - ... 12:05:38] "GET /img/pictur ...

Error: The data retrieval from a JSON file failed due to a type error. The program expected list indices to be

I am attempting to extract all latitude and longitude values from the provided JSON data. Below is the code snippet: import urllib.parse import requests raw_json = 'http://live.ksmobile.net/live/getreplayvideos?userid=' print() userid = 73589 ...

What is the most effective way to invoke a particular function/method within a Python script using Javascript (specifically, jquery/ajax)?

Just to clarify my setup: I am currently running this Python script as a cgi via the Apache web server. That part is working fine without any issues. However, my question pertains to how I can specify which function within the Python script should be execu ...

The wait.to_be_clickable() method in Selenium does not allow for immediate clicking

Currently, I am in the process of creating a test script to automate button clicks on dynamically inserted elements using ajax. However, I encountered an issue where after utilizing the wait.element_to_be_clickable method, the final element was not able to ...

The csv.reader function encounters issues when it is invoked inside the object provided as its parameter

While utilizing csv.reader(), I encountered a failure when calling it from a method within a class with the object itself as an argument (i.e., "self"). The error seems non-intuitive. Strangely, when I invoke csv.reader() from outside the object, everythin ...

Obtain the most recent values for 'n' columns within a grouped dataset using Pandas

Just stepping into the world of pandas, I find myself faced with a dataset for a job scheduler program: | Job Name | Region | Status | Timestamp | | some_job_1 | some_region_1 | DONE | 2018-10-02T03:46:25Z | | some_job_1 | some_regio ...

Guide on uploading a file using PUT in Python without the need to manually open the file

Issue: 1) I am looking for a Python library that allows me to provide the path of a file instead of opening it directly (especially if the file is large) in order to make a PUT request. 2) Additionally, I need this library to handle automatic redirection ...

Simultaneously managing both stepper motors and a camera

What is the optimal method for simultaneously controlling a stepper motor and camera? Imagine having a camera mounted on a linear stage driven by a stepper motor, with the goal of moving the stage in 1mm increments while capturing an image at the end of e ...

Generating a moving average in a pivot table as time progresses

I am working on creating a pivot table with a rolling average over two days using the `pivot_table()` function in Python. Currently, I am using `aggfunc='mean'` to calculate the average rating for each day. However, I need to adjust the mean calc ...

Python automation with selenium - capturing webpage content

I am utilizing selenium to scrape multiple pages while refraining from using other frameworks such as scrapy due to the abundance of ajax action. My predicament lies in the fact that the content refreshes automatically nearly every second, especially finan ...

The uncertain nature of data cardinality in Keras model predictions involving various time series and vector inputs causes confusion

My model takes in two inputs - a sequence of vectors and a simple vector, producing a simple vector as an output. For example: x1.shape: (50000,50,2) x2.shape: (50000,2) y.shape: (50000,2) The training and evaluation of my model using model.fit and model. ...

Experimenting with Selenium Webdriver to locate an input element by its name and input a specific value

I'm having trouble inputting a value in the final box. (Chassis Number) Here's what I've attempted: python from selenium import webdriver from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by imp ...

How can data be inserted into the Google App Engine database using a remote executable through programming?

I am interested in automatically populating and updating data in my Google Appengine database on a regular basis. I am looking to develop a program using Java and Python that can establish connection with my GAE service and feed information into my databa ...

Steps for a clean uninstall of Jupyter, erasing all remnants as if it had never been installed

After completely messing up my base (root) environment and the Jupyter installation within it, I am looking to start fresh by doing a complete reinstallation. However, in order to do so, I first need to fully remove Jupyter from my system. Despite trying t ...

I am having trouble finding the tabFrame frame shown in the screenshot below

https://i.stack.imgur.com/wCJhN.png I'm having trouble finding the frame labeled tabFrame in the screenshot provided. I did manage to locate outlookFrame successfully. This is the code I used: driver.switch_to.frame('outlookFrame') However ...