在docker里使用cron

cron是*nix操作系统上的一个计划任务管理工具。

使用方法

cron命令是一个服务程序,在后台运行任务。可以使用-f使它保持在前台。

crontab命令用来管理任务。

开始

直接从创建一个最简单的Dockerfile开始。

1
2
3
4
5
6
7
8
9
10
11
12
13
FROM ubuntu:20.04

# install cron
RUN apt-get update && apt-get -y install cron

# touch log file for tail
RUN touch /root/cron.out

# add the cron job
RUN echo "* * * * * echo hello from cron job >> /root/cron.out 2>&1" | crontab -

# go
CMD cron && tail -f /root/cron.out

运行结果:

1
2
3
4
5
6
> docker build -t first .
> docker run -it --rm first
hello from cron job
hello from cron job
hello from cron job
hello from cron job

使用sh

接下来我们试试使用cron运行sh

新建一个out_time.sh

1
2
now=$(date +"%T")
echo "Current time : $now" >> /root/cron.out

搭配dockerfile:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
FROM ubuntu:20.04

# install cron
RUN apt-get update && apt-get -y install cron

# copy sh
COPY out_time.sh /root/out_time.sh

# touch log file for tail
RUN touch /root/cron.out

# add the cron job
RUN crontab -l | { cat; echo "* * * * * bash /root/out_time.sh"; } | crontab -

# go
CMD cron && tail -f /root/cron.out

运行结果:

1
2
3
4
5
> docker build -t use_sh .
> docker run -it --rm use_sh
Current time : 06:09:01
Current time : 06:10:01
Current time : 06:11:01

使用cron file

这次我们将cron job写在文件里。

新建cronfile

1
2
* * * * * bash /root/out_time.sh

如果使用cron file,这里有两点需要注意:

  1. 最后一行一定要有个空行
  2. 文件的回车格式为LF,不能是CRLF

搭配dockerfile:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
FROM ubuntu:20.04

# install cron
RUN apt-get update && apt-get -y install cron

# copy sh and cron file
COPY out_time.sh /root/out_time.sh
COPY cronfile /root/cronfile

# touch log file for tail
RUN touch /root/cron.out

# add the cron job
RUN crontab /root/cronfile

# go
CMD cron && tail -f /root/cron.out

效果与把命令直接在Dockerfile里一致。

最后完整的来个starter

test.py

1
2
3
4
5
6
import datetime
from pandas import DataFrame

now = datetime.datetime.now()
df = DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]}, index=[now, now + datetime.timedelta(days=1), now + datetime.timedelta(days=2)])
print(df)

requirements.txt

1
pandas

Dockerfile

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
FROM ubuntu:20.04

# use mirror for apt
RUN sed -i 's/http:\/\/archive.ubuntu.com\/ubuntu\//http:\/\/mirrors.cloud.tencent.com\/ubuntu\//g' /etc/apt/sources.list
RUN sed -i 's/http:\/\/security.ubuntu.com\/ubuntu\//http:\/\/mirrors.cloud.tencent.com\/ubuntu\//g' /etc/apt/sources.list

# install cron and python3
RUN apt-get update && apt-get -y install cron python3 python3-pip
RUN link /usr/bin/python3 /usr/bin/python

# set workdir
WORKDIR /app

# pip install
COPY requirements.txt requirements.txt
RUN pip install -i https://repo.huaweicloud.com/repository/pypi/simple -r requirements.txt

# copy python files
COPY . .

# touch log file for tail
RUN touch cron.out

# add the cron job
RUN crontab -l | { cat; echo "* * * * * python /app/test.py >> /app/cron.out"; } | crontab -

# go
CMD cron && tail -f cron.out