#1 Python 定时任务的简单部署

2018-12-20

部署

# curl: (35) SSL connect error
# StackOverflow: You are using a very old version of curl.
# yum upgrade curl

# 安装 pyenv
curl -L https://github.com/pyenv/pyenv-installer/raw/master/bin/pyenv-installer | bash

# 环境变量
PYENV_ROOT="$HOME/.pyenv"
PATH="$PYENV_ROOT/bin:$PATH"
eval "$(pyenv init -)"
eval "$(pyenv virtualenv-init -)"

# 可用版本列表
pyenv install -l
# 使用国内 Python 镜像,相当于给 pyenv 加速
wget https://mirrors.sohu.com/python/3.6.7/Python-3.6.7.tar.xz -P ~/.pyenv/cache/
# 安装(优先使用缓存目录中的文件,会检查缓存校验码是否正确)
pyenv install 3.6.7

运行方式

假定:

  • 项目路径:/path/to/project/
  • 定时任务命令:python main.py

crontab 配置

早上 01:15 执行某某定时任务:

15 1 * * * /bin/bash /path/to/project/cron.sh

脚本 cron.sh

pyenv + pip 模式

#!/bin/bash

# 环境变量
PYENV_ROOT="$HOME/.pyenv"
PATH="$PYENV_ROOT/bin:$PATH"
eval "$(pyenv init -)"
eval "$(pyenv virtualenv-init -)"

cd /path/to/project/

# 创建并激活虚拟环境,安装依赖
# $PYENV_ROOT/versions/3.6.7/envs/tasks/
pyenv virtualenv 3.6.7 tasks

if [ $? -ne 0 ]; then
    pyenv activate tasks
    pip install -r requirements.txt
else
    pyenv activate tasks
fi

# 运行脚本
python main.py

pyenv + pipenv 模式

#!/bin/bash

# 环境变量
PYENV_ROOT="$HOME/.pyenv"
PATH="$PYENV_ROOT/bin:$PATH"
eval "$(pyenv init -)"
eval "$(pyenv virtualenv-init -)"

cd /path/to/project/

# 选择 Python 版本
pyenv local 3.6.7

pip show pipenv > /dev/null

if [ $? -ne 0 ]; then
    # 安装 pipenv
    pip install pipenv
    # 创建虚拟环境,安装依赖
    pipenv install
fi

# 运行脚本
pipenv run python main.py