hgu*_*ser 7 command-line scripts cron
我正在使用scrapy来获取一些资源,我想让它成为cron
每30分钟开始一次的工作。
定时任务:
0,30 * * * * /home/us/jobs/run_scrapy.sh`
Run Code Online (Sandbox Code Playgroud)
run_scrapy.sh
:
#!/bin/sh
cd ~/spiders/goods
PATH=$PATH:/usr/local/bin
export PATH
pkill -f $(pgrep run_scrapy.sh | grep -v $$)
sleep 2s
scrapy crawl good
Run Code Online (Sandbox Code Playgroud)
正如脚本所示,我也试图杀死脚本进程和子进程(scrapy)。
但是,当我尝试运行脚本的两个实例时,较新的实例不会杀死较旧的实例。
如何解决?
更新:
我有不止一个.sh
scrapy脚本,它们以不同的频率在cron
.
更新 2 - 测试 forSerg
的答案:
在我运行测试之前,所有的 cron 作业都已停止。
然后我打开三个终端窗口,说它们被命名为 w1 w2 和 w3,并按以下顺序运行命令:
Run `pgrep scrapy` in w3, which print none.(means no scrapy running at the moment).
Run `./scrapy_wrapper.sh` in w1
Run `pgrep scrapy` in w3 which print one process id say it is `1234`(means scrapy have been started by the script)
Run `./scrapy_wrapper.sh` in w2 #check the w1 and found the script have been terminated.
Run `pgrep scrapy` in w3 which print two process id `1234` and `5678`
Press <kbd>Ctrl</kbd>+<kbd>C</kbd> in w2 (twice)
Run `pgrep scrapy` in w3 which print one process id `1234` (means scrapy of `5678` have been stopped)
Run Code Online (Sandbox Code Playgroud)
在这一刻,我必须使用pkill scrapy
id 来停止scrapy1234
更好的方法是使用包装脚本,它将调用主脚本。这看起来像这样:
#!/bin/bash
# This is /home/user/bin/wrapper.sh file
pkill -f 'main_script.sh'
exec bash ./main_script.sh
Run Code Online (Sandbox Code Playgroud)
当然,包装器必须以不同的方式命名。这样,pkill
只能搜索您的主脚本。这样您的主脚本就简化为:
#!/bin/sh
cd /home/user/spiders/goods
PATH=$PATH:/usr/local/bin
export PATH
scrapy crawl good
Run Code Online (Sandbox Code Playgroud)
请注意,在我的示例中,我使用的./
是因为脚本在我当前的工作目录中。使用脚本的完整路径以获得最佳结果
我已经用一个简单的主脚本测试了这种方法,该脚本只运行无限循环和包装脚本。正如您在屏幕截图中看到的,启动包装器的第二个实例会杀死以前的
你的脚本
这只是例子。请记住,我无法使用scrapy 来实际测试它,因此请根据您的情况进行调整。
您的 cron 条目应如下所示:
0,30 * * * * /home/us/jobs/scrapy_wrapper.sh
Run Code Online (Sandbox Code Playgroud)
的内容 scrapy_wrapper.sh
#!/bin/sh
cd /home/user/spiders/goods
PATH=$PATH:/usr/local/bin
export PATH
scrapy crawl good
Run Code Online (Sandbox Code Playgroud)
的内容 run_scrapy.sh
0,30 * * * * /home/us/jobs/scrapy_wrapper.sh
Run Code Online (Sandbox Code Playgroud)