How can i set a crontab to execute a mysql query and log the output?

三世轮回 提交于 2019-11-29 11:25:26
Lucas Matos

well, since the mysql was not working properly directly inside crontab (thought that i think that was a path issue like Alex Howansky said), i created a php file dealing this query and called the php in crontab, much easier, and give me the option to use conditions.

the cron job:

00 8,14,18,19,20,21,23 * * * /usr/local/bin/php /home/aikaforum/cata/public_html/cron_dup.php >> /cata/tmp/cron_dup.log 

the php:

<?php
$username="xxxxxxx";
$password="xxxxxx";
$dbname="xxxxxx";
$dbhost="xxxxx.xxxxx.com";
$query="delete from hotaru_posts where post_id in ( select post_id from ( select post_id from hotaru_posts a group by post_title having count(post_title) > 1 ) b )";
mysql_connect($dbhost,$username,$password);
@mysql_select_db($dbname) or die(strftime('%c')." Unable to select database");
mysql_query($query);
mysql_close();
echo strftime('%c')." ok!";
?>

Thanks for all the help.

execute the following in your cron configurations

echo "your_SQL_statement" | mysql --skip-column-names -udbuser -pdbpassword yourdb >> yourlog.log

I suspect that your script is working but isn't actually returning any output. Here's my local test:

 mysql -u username dbname -e "delete from posts" > foo             
 cat foo
 (empty file) 

Just to be clear, foo is an empty file. posts was not an empty table.

So, just to be more precise, I think that's the expected behavior of MySQL here, although I can't confirm this in their docs. If you want/need output here, you'll probably need to write a script to check your table before/after deleting.

You need to use the full path to scripts executed by a cronjob. For instance if the mysql binary's location is /usr/local/mysql/bin/mysql you'd use that in your cronjob.

00 16,18,19,20,21 * * * /usr/local/mysql/bin/mysql -h MY-DB-HOST.COM -u .....
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!