【问题标题】:Having issues passing counts in my scheduler function在我的调度程序函数中传递计数时遇到问题
【发布时间】:2018-06-02 02:16:14
【问题描述】:

我正在使用由 Dan Bader 构建的 schedule 包,但我不确定如何将计数器传递到包中。

这是如何使用它的基本示例:

def job(message="stuff"):
    print("I'm working on:", str(message))

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

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

所以这每 10 秒打印一次 I'm working on: stuff,这很好,但我的应用程序缺少的是一个计数器。我想计算每次运行作业并将其传递到我的函数中,但我无法弄清楚。

这是我最近的尝试:

def job(count = 0):
    print(count)

count = 0 

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

while True:
    schedule.run_pending()
    time.sleep(1)
    count += 1

我认为将 count 作为参数并在 while 循环中循环它会起作用,但它没有。

归根结底,我需要一个平台,让我能够在某个时间间隔内不断地运行一个函数,并跟踪该作业运行了多少次。

任何帮助将不胜感激

【问题讨论】:

    标签: python cron scheduled-tasks


    【解决方案1】:

    您可以使用像字典这样的可变对象来实现您想要的。 (你原来的 count 变量是一个整数,在 Python 中是不可变的。)以下工作:

    import schedule
    import time
    
    store = {'count': 0}
    
    def job(data):
        data['count'] += 1
        print(data['count'])
    
    schedule.every(10).seconds.do(job, store)
    
    while True:
        schedule.run_pending()
        time.sleep(1)
    

    【讨论】:

      【解决方案2】:

      嗯,不确定这是更明显的方式,但我会做类似的事情

      import schedule
      import time
      
      class Count(object):
      
          def __init__(self):
              self._count = 0
      
          def __str__(self):
              count = self._count
              self._count += 1
              return str(count)
      
      def job(count):
          print(count)
      
      count = Count()
      schedule.every(1).seconds.do(job, count)
      
      while True:
          schedule.run_pending()
      

      Count 的实例在打印时只会自增,所以如果您确定只在 job 中打印它,您可以跟踪它运行了多少次。

      唯一真正的专业 VS dict 解决方案是您不必在 job 中计算任何东西 - count 单独处理自己。


       编辑

      由于一些 SO 人似乎喜欢我的想法,即使(这显然是真的)它隐藏了计数器的某些功能方面(没有人希望处理在打印时增加整数的实例)这里有一个小更新,使它不那么棘手,不那么混乱,简而言之:更好。

      class CountLogger(object):
      
          def __init__(self):
              self._count = 0
      
          def log(self, message = ''):
              print('{}: {}'.format(self._count, message))
              self._count += 1
      

      它做了几乎完全相同的事情,但是调用CounterLogger.log() 来查看一个整数的递增就不那么令人费解了。

      只需将print(count) 替换为count.log()

      【讨论】:

      • 我喜欢这个想法 :) 不过,在一个更大的项目中,我会小心使用它,因为它隐藏了很大一部分功能。无论出于何种原因,只需一个字符串转换为多个字符串......把事情搞砸了。
      • 这在大多数情况下都有效,但如果我需要在某些计算中使用该计数。
      • 好吧,您可以使用我提出的两种解决方案:count._count 让您可以访问计数器的整数值。所以在while True 之后你可以进行计算
      • 它是一个我似乎无法更改的字符串值。抱歉,我不经常使用类,所以我可能会遗漏一些简单的东西。
      • 不,它是一个整数,你可以更新它:count = CountLogger(); count._count = 100; count.log() 将输出100:
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-02
      • 2021-05-23
      • 1970-01-01
      相关资源
      最近更新 更多