我本地安装部署了 jupyter notebooks,我希望我写的notebook能在本地crontab定时执行,有哪些办法?

bluesky1年前 ⋅ 1053 阅读
有以下两种办法,供您参考:

1. 使用 nbconvert 将 notebook 转化为 Python 脚本,然后使用 crontab 定时执行 Python 脚本。

首先使用 nbconvert 将 notebook 转化为 Python 脚本。在终端执行以下命令:

```
jupyter nbconvert --to script my_notebook.ipynb
```

这将生成一个 Python 脚本,命名为 my_notebook.py。然后使用 crontab 定时执行 Python 脚本。在终端执行以下命令:

```
crontab -e
```

在系统默认的编辑器中添加以下内容:

```
* * * * * /path/to/python /path/to/my_notebook.py >> /path/to/logfile.log 2>&1
```

这将每分钟执行一次 my_notebook.py,并将输出重定向到 logfile.log 文件中。

2. 直接在 crontab 中执行 jupyter notebook,然后在 notebook 中设置定时执行。

首先使用 crontab 定时启动 jupyter notebook。在终端执行以下命令:

```
crontab -e
```

在系统默认的编辑器中添加以下内容:

```
@reboot /path/to/jupyter-notebook >> /path/to/logfile.log 2>&1
```

这将在系统启动时启动 jupyter notebook,并将输出重定向到 logfile.log 文件中。

然后在 notebook 中设置定时执行。打开 notebook 并转到“Edit”菜单,“Edit Notebook Metadata”选项卡。在“metadata”字段中添加以下内容:

```
"autosave_interval": 180,
"kernelspec": {
  "display_name": "Python 3",
  "language": "python",
  "name": "python3"
},
"language_info": {
  "name": "python",
  "version": "3.6.4"
},
"schedule": {
    "type": "interval",
    "every": 60
}
```

这将在 notebook 中设置了一个每 60 分钟自动运行的定时任务。您可以根据需要自定义时间间隔和其他选项。

全部评论: 0

    相关推荐