Running Cronjob from a specific directory

纵饮孤独 提交于 2019-12-23 03:37:10

问题


I created a php script for generating RSS feeds which is to eventually be run via a Cronjob.

All the php files and the resulting RSS xml will be within a sub folder in a website. The php script runs fine on my local dev if I use terminal or the browser while within the same directory on my local development machine.

e.g. php /Library/WebServer/Documents/clientname/siteroot/rss/dorss.php

works fine as does navigating to the dorss.php file in Chrome.

The CronJob has executed though with errors related to the fact that it cannot find the files specified with require_once() which are located in the same folder as rss or in a subfolder of that.

Long story short I need to have the Cronjob run from within the same directory as the dorss.php file so it can reference the include files correctly.

My knowledge on setting up a cronjob is VERY limited so I wanted to ask if this is at all possible (Change directory before running command) to do this on the same command line of the crontab or if not how can it be achieved please?

The current cronjob command is

0 0,6,12,18 * * * /usr/bin/php /var/www/vhosts/clientname/stagingsite/rss/dorss.php

TIA John


回答1:


I don't know if there's a better solution, but I would suggest to write a bash script that changes to the correct directory before executing the PHP file, and use cron to execute this script. E.g:

#!/bin/bash
cd /Library/WebServer/Documents/clientname/siteroot/rss/
php dorss.php

Or even just:

#!/bin/bash
php /Library/WebServer/Documents/clientname/siteroot/rss/dorss.php

Save it somewhere and use cron to run that.




回答2:


You can change directory to the one you want and then run the php from that directory by doing this:

cd /var/www/vhosts/clientname/stagingsite/rss/
&&
/usr/bin/php dorss.php

It's easier than creating bash scripts, here is the result:

0 0,6,12,18 * * * cd /var/www/vhosts/clientname/stagingsite/rss/ && /usr/bin/php dorss.php


来源:https://stackoverflow.com/questions/17616158/running-cronjob-from-a-specific-directory

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!