【问题标题】:Schedule Python Function to Return Values of a Function调度 Python 函数以返回函数的值
【发布时间】:2019-09-19 14:53:19
【问题描述】:

我一直在寻找一种解决方案来获取在预定时间执行的函数的返回值。这是一个示例函数。

def get_data(dir):
    df = pd.DataFrame()
    file_name = "nofile"
    # The rest of the body of the code executes and updates the two variables df and file_name
    return df, file_name

我想做的是将这个功能安排在早上 6:00。如果在上午 6:00 执行“get_data()”后 _file_name_ 仍为“nofile”,则应在下午 6:00 重新执行该函数。就这样

 def sched():
    # Schedule at 6 AM
    # Here I cannot get the file_name as return value of get_data()
    if file_name == "nofile":
        # Schedule at 6 PM
        file_name = "nofile"

我不知道如何使用 APScheduler。请帮忙。

【问题讨论】:

  • 如果您能提供一些为 APScheduler 编写的代码,将会很有帮助。 This 是一个很好的例子,说明有人可以就他们的问题寻求帮助。您可以参考他们的代码,看看是否可以尝试执行。
  • 你说“# Here I cannot get the file_name as return value of get_data()”是什么意思?为什么不能在这里打电话给df, file_name = get_data(...)

标签: python schedule apscheduler


【解决方案1】:

我能想到的最佳解决方案是使用全局变量。安排您的函数始终在 18:00(下午 6 点)运行,并使用全局变量的值来检查它是否应该执行任何操作。

【讨论】:

    【解决方案2】:

    所以经过深思熟虑并牢记 Alex 的建议,我解决了这个问题。这是我的问题的解决方案。我想安排的功能如下所示:

    def get_data(dir):
        df = pd.DataFrame()
        file_name = "nofile"
        # The rest of the body of the code executes and updates the two variables df and file_name
        return df, file_name
    

    解决办法是:

    from apscheduler.schedulers.background import BackgroundScheduler
    
    if __name__ == "__main__":
        sched = BackgroundScheduler()
    
        @sched.scheduled_job('cron', hour=6, minute=0, second=0, timezone='Europe/Paris')
        def run_db1():
            download_directory = "D:/random_data"
            if not os.path.exists(download_directory):
                download_directory = os.mkdir(download_directory)
    
            df, flnom = get_data(download_directory)
            print("1st check")
            if flnom == 'nofile':
                @sched.scheduled_job('cron', hour=18, minute=0, second=0, timezone='Europe/Paris')
                def run_db2():
                    download_directory = "D:/random_data"
                    if not os.path.exists(download_directory):
                        download_directory = os.mkdir(download_directory)
                    df, flnom = get_data(download_directory)
                    print("2nd check")
                    flnom = "nofile"
    
                    return df, flnom
    
            return df, flnom
    
        sched.start()
    

    如果今天在服务器上上传了新文件,我最初的问题是从 ftp 服务器下载数据。如果文件存在,则 file_name 将被更新;否则它将保持为“nofile”,并将在同一天晚些时候再次检查。 感谢所有贡献的人。

    【讨论】:

      猜你喜欢
      • 2022-07-21
      • 2018-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-12
      相关资源
      最近更新 更多