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

后端 未结 4 804
南旧
南旧 2020-12-19 13:50

Well, title self describes it.. I need to run a sql function to clean some duplicated posts, i need to do it several times a day so i need to use cron...

I set a new

相关标签:
4条回答
  • 2020-12-19 14:30

    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.

    0 讨论(0)
  • 2020-12-19 14:31

    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.

    0 讨论(0)
  • 2020-12-19 14:31

    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 .....
    
    0 讨论(0)
  • 2020-12-19 14:34

    execute the following in your cron configurations

    echo "your_SQL_statement" | mysql --skip-column-names -udbuser -pdbpassword yourdb >> yourlog.log
    
    0 讨论(0)
提交回复
热议问题