# 四、 Flask 定时任务



基于 APScheduler 包、Celery 的实现，甚至是在后台线程中构建的本土解决方案。遗憾的是，这些选择都不是很好，在本文中，我将向您展示我认为基于[Flask CLI](https://flask.palletsprojects.com/en/1.1.x/cli/)和[cron](https://en.wikipedia.org/wiki/Cron)服务的非常强大的实现。

```python
import time
from datetime import datetime


@app.cli.command()
def scheduled():
    """Run scheduled job."""
    print(str(datetime.utcnow()), 'Importing feeds...')
    time.sleep(5)
    print(str(datetime.utcnow()), 'Users:', str(User.query.all()))
    print(str(datetime.utcnow()), 'Done!')
```

```python
(venv) $ flask scheduled
2020-06-28 23:03:25.597371 Importing feeds...
2020-06-28 23:03:30.599382 Users: []
2020-06-28 23:03:30.621601 Done!
```

更多帮助

```shell
(venv) $ flask --help
Usage: flask [OPTIONS] COMMAND [ARGS]...

  This shell command acts as general utility script for Flask applications.

  It loads the application configured (through the FLASK_APP environment
  variable) and then provides commands either provided by the application or
  Flask itself.

  The most useful commands are the "run" and "shell" command.

  Example usage:

    $ export FLASK_APP=hello.py
    $ export FLASK_DEBUG=1
    $ flask run

Options:
  --version  Show the flask version
  --help     Show this message and exit.

Commands:
  db         Perform database migrations.
  deploy     Run deployment tasks.
  profile    Start the application under the code...
  run        Runs a development server.
  scheduled  Run scheduled job.
  shell      Runs a shell in the app context.
  test       Run the unit tests.
```

如何将我的`flask scheduled`命令配置为作为 cron 作业每分钟运行一次：

```python
* * * * * cd /home/ubuntu/flasky && venv/bin/flask scheduled >>scheduled.log 2>&1
```
