Home > Software engineering >  Python: get next item from a list on a schedule
Python: get next item from a list on a schedule

Time:10-27

This is my first posted question; I am a new coder who is trying to make a fun quiz app for a friend using Flask, Jinja, and Python. In the quiz, you get 6 different clues each day that point you towards a specific answer (not multiple choice, a specific answer). I have a list with all the answers, and I am currently trying to get the next item in the list...but the problem that I'm running into is that I want this to happen on a schedule, every 24 hours. That's the hard part: I can print the next item in the list just fine, but I can't figure out how to then automatically print the next item at a specific time interval. Once I have that I think I'll be well on my way! (I really want to do this in Python, not JavaScript, because I know even less JavaScript than I do Python).

Here's several things I've tried:

import schedule
from schedule import every, repeat
import time

answers = ["answer1", "answer2", "answer3"]

@repeat(every(3).seconds)
def fetch():
    global answers
    answers  = 0
    print(answers)


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

This returns the error: 'int' object is not iterable.

I have also tried:

import schedule
import time


def job():


    answers = ["answer1", "answer2", "answer3"]

    for answer in answers:
        print(answer[0:])


schedule.every(10).seconds.do(job)

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

This just prints all the books at once; not what I want, I want a different one every interval (here 10 seconds, but in reality 24 hours).

Another thing I tried:

import schedule
import time


def job():


    answers = ["answer1", "answer2", "answer3"]

    answersIterator = iter(answers)
    print(next(answersIterator))

schedule.every(10).seconds.do(job)

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

This just prints the first item from the list on repeat; I want it to go through the list, but not all at once, at a specific interval.

I have read through as many tutorials as I can get my hands, but because I'm new at this I'm struggling. Apologies if there are formatting issues here; I read through the guidance before posting, but first time, etc. etc. Thanks all!

CodePudding user response:

Consider where you define variables and in which area they are valid. In the last attempts, for this reason, the iterators do not maintain their state. They are recreated each time the function is called and disappear again when the function is exited.

The following example defines a global iterator that starts over at the end of the sequence. Its state is preserved because it was not defined in the local scope of the function. Within your repeatedly called function you can now query the next element at regular intervals with next(iterator).

from itertools import cycle
from schedule import every, repeat, run_pending
import time

iter_answers = cycle(["answer1", "answer2", "answer3"])

@repeat(every(10).seconds)
def job():
    print(next(iter_answers))

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

However, I don't understand how you want to use the code inside Flask.
If I understood you correctly, the client should ask for an answer, which is updated and provided by the server at intervals. So you should think about how to write an endpoint that matches a timestamp and depending on that uses the next element in the sequence. So possibly something like this.

from flask import Flask
from datetime import datetime

class Provider:
    def __init__(self, items):
        self._i = 0
        self._t = datetime.now()
        self.items = items

    def next(self):
        if (datetime.now() - self._t).total_seconds() >= 10:
            self._i = (self._i   1) % len(self.items)
            self._t = datetime.now()
        return self.items[self._i]

provider = Provider([
    'answer1', 
    'answer2', 
    'answer3', 
])

app = Flask(__name__)

@app.route('/')
def index():
    return provider.next()
  • Related