Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to create a counter within each run of my job #189

Open
madhavthaker opened this issue Dec 19, 2017 · 2 comments
Open

How to create a counter within each run of my job #189

madhavthaker opened this issue Dec 19, 2017 · 2 comments

Comments

@madhavthaker
Copy link

Here is my code:

def job(count=0):
    print("I'm working on:", str(count))

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

count = 0
while True:

    schedule.run_pending()
    time.sleep(1)
    count += 1

So, I'm confused about how i'd pass that count within my function. In the future, I plan to create a running list of live values that are being appended along with a counter and i'm not sure how i'd go about doing that

@talaniz
Copy link

talaniz commented Mar 28, 2018

I would say you could either update global variables or write out to a data source like a text file or database. While global variables are not encouraged, I was able to get the following example working (borrowed from the docs) which prints out the counter result every 10 seconds when the job is run--

import time

counter = 0

def job():
    print("I'm working...")
    global counter
    counter += 1
    print("Counter = {0}".format(counter))

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

while True:

    schedule.run_pending()
    time.sleep(1)

@EEdLoh
Copy link

EEdLoh commented Jul 17, 2018

There's actually a super neat trick where modifications to mutable default parameters are persistent through multiple calls. Like if I had a program that read

def f(x=[0])
    print(x[0])
    x[0] += 1

for i in range(4):
    f()

I would get an output like

0
1
2
3

You could use this trick to keep a counter going on a job you had scheduled. Like:

def job(count=[0]):
    print("I'm working on:", str(count[0]))
    count[0] += 1

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

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants