Response
stringlengths
8
2k
Instruction
stringlengths
18
2k
Prompt
stringlengths
14
160
The cron syntax says to run the command at a fix time not after an interval.The */10 means execute the command if the modulo is 0In your case the code will be excecuted at second 0 of every 10 minutes at every hour at every day and so on.So your cron will be executed for instance at 09:00, 09:10, 09:20, 09:30 and so on.The only way I know with build in methods is to use something likesetTimeout(myFunc, 10 * 60 * 1000);An other option is to set a fixed cron running at the calculated correct time now +10 minutes with moment.js where you specify the exact execution time.Examplevar moment = require('moment') router.post('/getUser', function (req, res) { var cronString = moment().second() +' '+ moment().add(10,'minutes').minute() +' '+ moment().hour() +' '+ moment().day() +' '+ moment().month() +' *'; var task = cron.schedule(cronString, function () { console.log("cron job started") }, false); task.start(); })But beware of the fact that this would be executed every year at the same time ;)
I am trying to run a cron job after 10 minutes, sometimes it runs after 10 minutes and sometimes it runs after like 2 minutes when I call the webservice. Below is the coderouter.post('/getUser', function (req, res) { var task = cron.schedule('0 */10 * * * *', function () { console.log("cron job started") }, false); task.start(); })It should always runs after 10 minutes not like sometime 2 minutes as soon as the webservice is called.
cron job is not working node-cron
Include the full path touseraddin thesystem()call.Crontab does not get a copy of the environment, therefore thePATHenvironment variable isn't set.
I am working on a PERL script that adds users from a database and then deletes the database. The code works fine when I execute it.use DBI; use strict; my $database = "database"; my $hostname = "123.4.56.78"; my $port = "3306"; my $user = "user"; my $password = "password"; my $dsn = "DBI:mysql:database=$database;host=$hostname;port=$port"; my $dbh = DBI->connect($dsn,$user,$password) or die "Can't connect to database: ", $DBI::errstr, "\n"; my $sql = 'SELECT * FROM somewhere'; my $sth = $dbh->prepare($sql); $sth->execute(); while (my @row = $sth->fetchrow_array) { system("useradd -g mygroup -d /home/somewhere/$row[0] -s /sbin/nologin $row[0]"); system("echo $row[0]:$row[1] | chpasswd"); } my $sql_delete = 'TRUNCATE somewhere'; my $delete = $dbh->prepare($sql_delete); $delete->execute();However when I execute it through the Crontab, the system() statements are never executed, and the user are not added. They are deleted from the databse itself though.* * * * * perl /var/perl/myperl.plThe log says every minute:Jul 26 15:42:01 ex40 CROND[7028]: (root) CMD (perl /var/perl/myperl.pl)Any ideas?
Cron not executing my system() statement in PERL
As mentioned in comments, the following error:E486: Pattern not found: 2 * * * *Was caused because you were not editing properly. That is, you were sayingcrontab -ecorrectly and then you were entering invi. Instead of going into the insert mode, you would directly type*/2 * * * * /home/test/test/test.sh, whichviwould try to perform as a command, which is not.So what you have to do is to pressito enter in the write mode. And then, just then, write*/2 * * * * /home/test/test/test.sh. Finally, save the file by saying:wq.In case other problems occur in your cronjob, you may want to check the "Debugging crontab" section inhttps://stackoverflow.com/tags/crontab/info.
i am trying to run a shell script using cronjob after every 2 minutes. I opened my terminal then typedcrontab-eonce i execute this command i am writing my command*/2 * * * * /home/test/test/test.shbut i am getting an error asE486: Pattern not found: 2 * * * *please help as i am new to this and i don't know why it is happening. If you give me any links and code on hwo to execute cronjob it would help.
Cron job with shell script
Cron doesn't magically make the program "run forever". Start the program manually. It will probably take 1-2 seconds to run, then exit. This is exactly what happens when running with cron, as well. So, unless you run ps the second your program gets started, you won't see anything in the process list.Your loop 1..5 won't help, as after the files are deleted in the first round, the rest is effectively a no-op.
This is my Java file for which I have created Delete.jarimport java.io.*; public class Delete { public static void main(String[] args) { try{ int i =1; while(i<5){ File directory = new File("downloads"); System.out.println("I am running"); for(File file: directory.listFiles()) file.delete(); i++; } }catch(Exception e){ e.printStackTrace(); } } }This is my Script to run the jar file if it is not running#!/bin/bash processid=`pgrep -f 'Delete.jar high'` echo "Processes:"$processid if [ -n "$processid" ] then echo "Process is running. No action will be taken" else echo "Process is not running. Executing ResponseHandler-fast now !" cd /home/ubuntu/; java -jar Delete.jar high fiThis is line I have added to my crontab -e* * * * * sh /home/ubuntu/check.shI rebooted my System I was expecting that my script will run check that jar is not running and it will run it but it is not doing so. What I am doing wrong here.If I execute ps after 2 -3 minutes still I am not getting java as an entry.Thanks.
Cron job not running the jar
The recommended method is using scheduled queries. You create a 'pack' like one of theseGitHub linkwhich includes the queries and frequencies. Then update the osqueryd config to include the pack.
I'm very new to OSQuery and i'd like to execute a query (e.g.SELECT * FROM last) every 5 minutes. Is there any chance, to define a script, which executes this routine in within a crontab or something else like this?Probably it should be enough to execute the script with the query as parameter, but there is nothing in the documentation, so i guess, it won't be supported yet.I checked their Community and also their FAQ but haven't found something relating to my problem.OSQuery is currently on the latest version (1.7.3), self compiled, running on Ubuntu Server, 64 bit 15.10.If you need more information to help me, just let me know.
How to execute a query every 5 mins
Rather than create the file in the directory, why not create it somewhere else? Then after the data's been written, just move it into the webroot and overwrite the previous set.Example:sh create_some_data.sh > /home/cronuser/my_data.html mv /home/cronuser/my_data.html /var/www/
I have a small program that runs and generates a new text dump every 30sec-1min via cron.program > dump.txtHowever I have another PHP web program that accesses the text dump in a read-only mode whenever someone visits the webpage. The problem is that I believe if someone accesses the website the very second the cron job is running the webpage may only read half the file because i think Linux does not lock the file when>is used.I was thinking of doing:echo "###START###" > dump.txt program >> dump.txt echo "###END###" >> dump.txtThen when the PHP webpage reads the dump in memory, I could do a regex to check if the start and end flags are present and if not, then to try again until it reads the file with both flags.Will this ensure the files integrity? If not, how can I ensure that when I readdump.txtit will be intact.
reading a file created from a cron job
Cron implicitly runs the line given withsh -c.If that line starts another shell (without recognizing it as the only command to run and implicitly making it anexecoperation, an optimization some but not all shells will implicitly perform), then yes, you have two shells.To have your first shellexecthe second one, replacing its image in memory and inheriting its PID, consider using the following line in your cron job:exec /home/amit/Desktop/crontest/test.sh >/home/amit/Desktop/crontest/null 2>&1
I have one simple script which echoes value of for loop. I am calling same using a cron job and I ran grep command it shows two instances.Script::#!/bin/bash for i in {1..999999} do echo "Welcome $i times" doneCron Command::* * * * * /home/amit/Desktop/crontest/test.sh > /home/amit/Desktop/crontest/null 2 >&1.ps Grep command::$ ps -ef | grep test amit 5853 5852 0 23:28 ? 00:00:00 /bin/sh -c /home/amit/Desktop/crontest/test.sh > /home/amit/Desktop/crontest/null 2>&1 amit 5854 5853 99 23:28 ? 00:00:07 /bin/bash /home/amit/Desktop/crontest/test.sh 2My question is::It's really a two instance or it just a way how cron job run.
Two Shell Script instance while calling through cron job
We need more information to troubleshoot this issue. Namely, you will need to monitor /var/log/syslog and spot errors regarding that cronjob. It is probably also good practice to output an error log for this job.
I use centOS, at command line, I execute>./tv.pyscript and it runs correctly.But, when I include into/etc/crontab, entry*/30 * * * * /root/tv.py, it does not.What am I doing wrong?This is the head of script:#!/usr/bin/env python # -*- coding: utf-8 -*- from bs4 import BeautifulSoup
crontab can not running python script
Depends on your needs. In most cases, cron-run PHP (or Perl or bash or any) scripts are way easier to debug, because they can be run independent from cron, and cron already provides the time control you would otherwise have to provide yourself.Daemons are useful if you want to encapsulate your functionality into a single program, for example if it switches between different states and the like. But in most cases you will have to find a way to ensure that your daemon is still running.I am not talking about server daemons, because thats not achievable with cron-triggered PHP scripts, and is a complex topic on its own.
Which technique is better to be used for running background processes on linux server.Php Cron or Linux Daemon ?May be written in perl .etc. Just want some advice in view of performance and stability ?
Which is better for running background processes . Php Cron or Linux Daemon?
So, I ended up posting this same question on Ask Ubuntu:https://askubuntu.com/questions/687423/use-crontab-to-restart-an-upstart-service-on-scheduleIn summary, the correct way to schedule a restart of theshiny-serverin Ubuntu 12.04 (which uses Upstart) is to add the following entry to yourrootuser'scrontab:0 6 * * * /usr/sbin/restart shiny-serverCredit goes to @earthmeLon for helping me figure this out. Hope this helps somebody in the future!
I'm having a bit of trouble gettingshiny-serverto restart viacrontab. So far, I have tried 2 ways:1) Created bash script withrestart shiny-serveras the last line, and added tocrontab. Additionally, there's SQL code that pre-processes data within this script.0 15 * * * bash /home/local/ANT/raybao/load.sh2) Added a line tocrontab -eforrootuser like the following:0 15 * * * restart shiny-severI added toroot crontabas opposed to my own user's simply because you need tosudo restart shiny-serverotherwise.Oddly, all the SQL code within #1 above successfully runs and is logged, however theshiny-serverprocess is not restarted. If I simply do:sudo -iand thenrestart shiny-server, it works so I'm baffled.Any ideas on how to solve this?
Restarting Shiny Server with crontab
The answer is probably option 3. Use-delete.30 23 * * * root find /var/www/html/site/reports/ -name '*.pdf' -type f -mtime +30 -deleteBoth the options in the question spawn sub-shells to do the deletion work which this option avoids entirely.The portability of-deleteis somewhat limited. GNUfindsupports it as does FreeBSDfind(at least according tothis man page) but OpenBSDfinddoesn't appear to. I don't know about any others.As user3159253 says in their comment among the first two options the first is likely somewhat faster due to requiring fewer invocations ofrmbut is not safe for filenames with newlines in them (and possibly a handful of other characters but I'm not sure).A modification of the second option to use-exec rm {} \+will be better as well as it will also reduce the number of invocations ofrmby giving it multiple files at once and may or may not be better than the first option at that point but will still not beat the option given here.
I have to delete all the pdf files which are more than 30 days old at 11:30 PMThe below given are the two working cronjobs in/etc/crontab30 23 * * * root find /var/www/html/site/reports/ -name ".pdf" -type f -mtime +30 | xargs -I {} rm -f {} \; 30 23 * * * root find /var/www/html/site/reports/ ( -name ".pdf" ) -type f -mtime +30 -exec rm {} \;I would like to know which one is better among the two and the reason.Please help.
Two crons doing same job in linux, which one is better
It could be because your script is running in a plain POSIX shell rather than bash.(( ))is a bash extension, and if you run thatif (( ... )); thenline in a shell that doesn't have it, it'll create a subshell of a subshell to run the command$linecount > $max_lines-- which means it tries to execute15222as a command, with output redirected into a file named "50000". Not what you wanted at all.As for why this happened... my guess is that it's because you had a space before the shebang (#!/bin/bash). In order for a shebang to be recognized by the OS, the "#!"mustbe the first two bytes of the file. Since that wasn't recognized, cron probably fell back to running it with /bin/sh. When you run it from the command line, you're using bash, and its fallback is to use itself.
I have written a small bash script to archive my .bash_history file, to allow me to keep the regular .bash_history file reasonably small, but keep the history in a .bash_history.archive file forever. When I run it from the command line, it works just fine, but when it runs from a crontab (on Ubuntu 12.04 and 14.04), it fails with an error message like this:/usr/local/bin/archive_bash_history: 7: /usr/local/bin/archive_bash_history: 15222: not foundThe script is:#!/bin/bash umask 077 max_lines=50000 linecount=$(wc -l < ~/.bash_history) if (($linecount > $max_lines)); then prune_lines=$(($linecount - $max_lines)) head -$prune_lines ~/.bash_history >> ~/.bash_history.archive \ && sed -e "1,${prune_lines}d" ~/.bash_history > ~/.bash_history.tmp$$ \ && mv ~/.bash_history.tmp$$ ~/.bash_history fithe 15222 number is the number of lines in the .bash_history file when it runs.
Why does my if statement fail when run within a crontab on Ubuntu (12.04 and 14.04)?
Long time ago, it happened on some systems thatcrondidn't start shell scripts, only binaries. So you had to indicateexplicitelywhich interpreter to use in the crontab line*/1 * * * * /bin/bash /var/www/ErnestynoFailai/scripts/write_DHT11_to_db.shI didn't check since, and I dont know what system you are using. On debian/jessie, it is told in the crontab 5 manpage that the command is executed by/bin/sh, or the shell specified by theSHELLvariable in thecrontabfile.Seehttps://superuser.com/questions/81262/how-to-execute-shell-script-via-crontab
When I type the following in a terminal./DHT 11 4it works and saves all data to mysql correctly.id (1), temp (29), hum (37), date (2015...)When I add it to a crontab it does not work correctly.id (1), temp (0 or empty), hum (0 or empty), date (2015...)sh script:#!/bin/bash #DHT11 SCRIPT="/var/www/ErnestynoFailai/scripts/DHT 11 4" #DHT22 #SCRIPT="/root/to/folder/DHT 22 4" #AM2302 #SCRIPT="/root/to/folder/DHT 2302 4" TEMP_AND_HUM="" while [[ $TEMP_AND_HUM == "" ]] do TEMP_AND_HUM=`$SCRIPT | grep "Temp"` done TEMP=`echo "$TEMP_AND_HUM" | cut -c8-9` HUM=`echo "$TEMP_AND_HUM" | cut -c21-22` myqsl_user="root" myqsl_pw="pw" myqsl_database="DHT" today=`date +"%Y-%m-%d %T"` query="INSERT INTO DHT11 (temp, hum, date) VALUES ('$TEMP', '$HUM', '$today');" mysql --user=$myqsl_user --password=$myqsl_pw $myqsl_database << EOF $query EOFAnd crontab:*/1 * * * * /var/www/ErnestynoFailai/scripts/write_DHT11_to_db.shWhat can be wrong?
Crontab can't loop
destroy_allreturns an integer and you cannot concatinate strings and integers like that. A simple example to show this problem is:"foo" + 42 + "bar" TypeError: no implicit conversion of Fixnum into StringThe solution is to use string interpolation (or theto_smethod, but that feels ugly to me):puts "Done. #{destroyed.length} records deleted."
I have a standard has_many/belongs_to relationship with movies and posters. Each movie can have many posters. I have the following in a rake command:task remove_movie_posters: :environment do destroyed = Movie.where(fake: true).posters.where("created_at < ?", 1.minute.ago).destroy_all puts "Done. " + destroyed.length + " records deleted." endbut I get the error:TypeError: no implicit conversion of Fixnum into String
Destroy all issue
To make sure the require_once will always work, you could usedirname(__FILE__)+ the path relative to the getProviders.phpIn your case this would be:require_once(dirname(__FILE__)."/../ClassLoader.php");
I have Apache running on Debian with PHP 5.4.PHP-cli is installed.My directory structure for the web project is:- /myproject - /src - /controller - getProviders.php - /model - /public - ClassLoader.phpI want to create a cron job to execute getProviders.php every 5 minutes. This is as far as I have come:*/5 * * * * /usr/bin/php /var/www/myproject/src/controller/getProviders.phpIt doesn't work because I have a require_once in getProviders.php requiring ClassLoader.php, but he can't find it.require_once "../ClassLoader.php"getProviders.php works when executed via URL.I'm not new to PHP development, but new at configuring the server around it. What do I have to do to make it work. I'm guessing I have to set the include path, but I have no idea to what exactly.Thanks in advance for your help.
Creating a cron job with PHP and Apache
I don't see the point to add a cron job which then starts a loop that runs a job. Either use cron to run the job every minute or use a daemon script to make sure your service is started and is kept running.To check whether your script is already running, you can use a lock directory (unless your daemon framework already does that for you):LOCK=/tmp/script.lock # You may want a better name here mkdir $LOCK || exit 1 # Exit with error if script is already running trap "rmdir $LOCK" EXIT # Remove the lock when the script terminates ...normal code...If your OS supports it, then/var/lock/scriptmight be a better path.Your next question is probably how to write a daemon. To answer that, I need to know what kind of Linux you're using and whether you have things likesystemd,daemonize, etc.
How do I avoid cronjob from executing multiple times on the same command? I had tried to look around and try to check and kill in processes but it doesn't work with the below code. With the below code it keeps entering into else condition where it suppose to be "running". Any idea which part I did it wrongly?#!/bin/sh devPath=`ps aux | grep "[i]mport_shell_script"` | xargs if [ ! -z "$devPath" -a "$devPath" != " " ]; then echo "running" exit else while true do sudo /usr/bin/php /var/www/html/xxx/import_from_datafile.php /dev/null 2>&1 sleep 5 done fi exitcronjob:*/2 * * * * root /bin/sh /var/www/html/xxx/import_shell_script.sh /dev/null 2>&1
Check processes run by cronjob to avoid multiple execution
The most efficient way to do this is to use a view. Huh? What does that have to do with the problem? Well, don't do the delete 10 minutes after wards. Instead, create a view with the following logic:create view v_recoveries as select r.* from recoveries r where expiry > date_sub(now(), interval 10 minutes);For performance, you want an index onrecoveries(expiry), so this should be fast.Then, at your leisure -- once per date, or once per hour, or once per week -- delete unneeded records with:DELETE FROM `recoveries` WHERE `expiry` <= date_sub(now(), interval 10 minutes);This approach has several advantages:The presence of data is exactly 10 minutes, rather than based on the scheduling of some job.The actual deletions can take place when the system is quiescent.If a cron job fails to execute, the data is not "corrupted" -- that is, you do not get data that is too old.If the system is busy (lots of inserts), then the inserts are not competing with deletes, further slowing the system down.
I have a password recovery system that allows users to recover their password by email. The details for each request are inserted into myrecoveriestable, and are deleted upon successful recoveries. I have a timestamp for each recovery that is set 10 minutes after the creation of each recovery.I want to implement a system that will automatically delete each expired recovery after 10 minutes. Since this expiry time will be different for every row, it means that using a cron job would be incredibly ineffective in performing this task.What is the most efficient way to achieve this?Here's my code:$time = time(); $recoveries = DB::fetch("DELETE FROM `recoveries` WHERE `expiry` <= ?;", array($time));
Most efficient method to expire records after 10 minutes from creation
You can make it conditional:41 17 * * * cd /var/log/crmpicco-logs/; s=$(find . -mtime 0 -exec grep -E "error|Warning|Error|Notice|Fatal" {} +); [[ -n "$s" ]] && echo "$s" | mail -s "Errors/Warnings from Logs"[email protected]
I have the following entry in my Crontab which willgrepmy logs for any instance of error, warning, notice etc...41 17 * * * cd /var/log/crmpicco-logs/; grep -E "error|Warning|Error|Notice|Fatal" $(find . -mtime 0 -type f) 2>&1 | mail -s "Errors/Warnings from Logs"[email protected]What I would like to do is tweak it so that it only executes themailcommand if the output from thegrepsearch returns a result. So, if it's empty then I don't want to receive an email.
Check if output from grep is empty before sending email from Crontab
You cannot change variables in a different process like that. Probably the nearest you can do is to use a file, something like this.Incrontab:* * * * * /bin/date > /tmp/value.txtIn some other script:#!/bin/bash while :; do v=$(cat /tmp/value.txt) echo $v sleep 1 done
This question has boring me a whole day...I want to modify root's environment variables $bai automatically, and I write a shell script and add it to root's crontab. but $bai is not changed.here is my script /root/111.sh:#!/bin/bash time=`date` export bai=$timehere is the crontab:*/1 * * * * . /root/111.shThenecho $baiis nullbut when Isource /root/111.shandecho $bai, it can get the time:Wed Dec 24 17:02:48 CST 2014So how can I get the environment variables by use it in my cron job?
Use crontab job to modify global environment variables
Might be that yournodecannot be found whencronis running; becausecronhas a limited search path. Try prefixing it with wherever you havenodeinstalled, so e.g., instead ofnode /home/pi/Sites/node-raspberry-pi/index.js 3000you would get/usr/local/bin/node /home/pi/Sites/node-raspberry-pi/index.js 3000You can also extend the searchpath forcron, seeman 5 crontab. Hope this helps..
I have a simple question. I try to run a Node JS program on a Cron task via a bash script.So, on crontab -e, I made a task @reboot that execute boot.sh :# m h dom mon dow command @reboot bash /home/pi/boot.shAnd my bash script :#!/bin/sh set -e cd /home/pi/Sites/node-raspberry-pi/ /usr/bin/git pull node /home/pi/Sites/node-raspberry-pi/index.js 3000 # where 3000 is the argument of my program exit 0When I dobash /home/pi/boot.sh, it works as supposed.What do I miss ?Note : bothcrontab -eandbash /home/pi/boot.share exectued aspiuser.
Running Node as Cron task
Your can export library path in your .bash_profile likeexport LD_LIBRARY_PATH=$ORACLE_HOME/libor you can copy your libclntsh.so in /usr/lib/ or /lib
Error while loading shared libraries: libclntsh.so.11.1 : cannot open shared obj file no such file. When running from crontab.I complied my c++ program, its a proc program after compiling proc I will run the below command.g++ filename.CPP -I $ORACLE_HOME/precomp/public -L $ORACLE_HOME/lib -lclntsh -o testI created a crontab to run it every min$ crontab -l * * * * * /home/test > /home/te.txt 2>&1I made a symbolic link of that library. But I'm getting above error inside te.txtIm searching this for past 2 days and also went through the similar question, but still I not able to clear the error.I'm not sure withLD_Library_pathor.bash_profile. how to include that library.
Error loading shared libraries libclntsh.so.11.1 cannot open
To me, the easiest solution would be something like this:func (e SomeStruct) Run() { t := time.Now().Local() day_num, _ := t.Day() if day_num <= 7 { fmt.Println("Hello, playground") } } func init() { revel.OnAppStart(func() { jobs.Schedule("0 0 * * 1", SomeStruct{}) })Where you simply run the job EVERY monday, but in the job itself, check if it's the FIRST monday before you actually do anything. There may be a better way (not very familiar with Revel), but glancing through how their jobs work this would work and it's not like it will be a performance issue.
I'm using golang revel and I need a job to be run every first monday of every month, a quartz cron spec for that would look like this: 0 0 0 ? 1/1 MON#1But robfig/cron doesn't accept a spec like that, hence neither revel/jobs. Anyone knows how can I solve that [using revel jobs]?
Golang Revel Job spec every 1st monday on every month
You have one more * than required in your crontab entryTry0-59 * * * * php -f /Documents/Programs/WeeklyHours/weekly_hour.phpThe 0-59 is so that it will run every minute
What is wrong with this cronjob?* * * * * * php -f /Documents/Programs/WeeklyHours/weekly_hour.phpI have combed through the various cron questions on StackExchange and nothing is working. When I run php -f /Documents/Programs/WeeklyHours/weekly_hour.php in the terminal it works perfectly. I know the cron jobs are running because I am getting error mail. At the bottom of the error mail messages it is saying "/bin/sh: Applications: command not found." Any ideas on what I am doing wrong?Thanks in advance.
Running php script using cron on a Mac
9 * * * /path/to/your/cron/scrip >/dev/null 2>&1Your cron job will be run at: (5 times displayed)2014-10-14 09:00:00 UTC 2014-10-15 09:00:00 UTC 2014-10-16 09:00:00 UTC 2014-10-17 09:00:00 UTC 2014-10-18 09:00:00 UTCreferCronjob Generator
I am trying to setup my cron jobs to run only once a day at 9 am.This is what I am using now:Minute Hour Day Month Weekday 0 0,09 * * *The problem is that it runs 2 times a day: - at midnight 00:00 - and at 09:00How can I make it to run only at 09:00 (once a day)?
Cron Jobs in cPanel - run once a day at 9 am
The error suggests that you fire the commandpython manage.py mycustomcommandfrom within the Python interpreter(and not as a bash command).You probably have something like1 * * * * python /path/to/myscript/test.shin your crontab entry which is a mistake and it should be1 * * * * /path/to/myscript/test.shinstead.
I'm trying to schedule a script with cron in kubuntu. If I execute the script manually line by line, it goes just fine, but scheduled with cron it raises the following SyntaxError:File "/opt/django/myproject/myapp/cron/test.sh", line 4 python manage.py mycustomcommand ^ SyntaxError: invalid syntaxThe content of the script test.sh is as following:#!/bin/bash source /opt/virtualenvs/myvirtualenv/bin/activate cd /opt/django/myproject python manage.py mycustomcommandBasically the script activates a virtual enviroment where django is installed, then accesses to my project path, and then executes a custom django command. As said, this works fine if I do it manually.I tried to schedule the script in cron with normal and root permissions also ("crontab -e" and "sudo crontab -e")Any idea? Thanks!
SyntaxError if executed with cron, OK if manually
The first line of the script should be:<?phpYou may have short tags enabled in the Apache PHP configuration, but not the CLI PHP configuration.
I know that this question was asked many times, but most of the answers are not really useful.So I edited crontab withcrontab -e. It was empty and I added just one line*/1 * * * * php5 /var/www/cron.phpwhich I think will be executing cron.php every 1 minute. I saved the file, but it clearly is not executed (inside my php file I have only<? $file = 'test.txt'; file_put_contents($file, "Work");and it is not created. I looked and modified permissions on cron.php to 777. Php is installed as apache module.What bothers me is that when I dophp5 /var/www/cron.phpfrom command line, I just see the content of the file and it not executed.What am I doing wrong?I also tried using full path with*/1 * * * * /usr/bin/php5 /var/www/cron.phpbut also with no luck.
Cronjob does not work
Try this:0 * * * * /bin/bash -l -c 'cd your_app_path && RAILS_ENV=production bundle exec rake your_task'Or, it is good to usewhenevergem if you want to do command line rails work in cron.
I am trying to run rake task in cron job like this0 * * * * cd /var/www/rails_path/rails && rake my_task RAILS_ENV=productionI can run this commandcd /var/www/rails_path/rails && rake my_task RAILS_ENV=productionfrom shell and got result.And I checked the cron log the commond did get run. But in fact the rake task didn't get run when the cron job excutes (the task should have logs, I didn't see logs of this rake task after cron job ran).What is the issue?UPDATED:tried0 * * * * /bin/bash -l -c "cd /var/www/rails_path/rails && rake my_task RAILS_ENV=production"no luckinstalledwhenevergem and haveevery 2.minutes do rake "my_task" endin ./config/schdule.rb. It was not running at all (I deployed rails in nginx with passenger).Thanks
rails : running rake task in cron job
+50The error in the logs seem to be saying that the bundle command cannot be found. Meaning the bundler gem is not installed or something.It should be related to thisquestion in SO. You can follow the link within to the OpenShift Bug Report.The problem is that with the previous OpenShift update, the Ruby 1.9 cartridge is supposed to be using Ruby 1.9.3 but it somehow got changed to Ruby 1.8 instead. Thus, many of the gems installed with Ruby 1.9 will not be found when it is using Ruby 1.8. The workaround is to export the PATH and LD_LIBRARY_PATH in the cron script (refer to the bug report).Noticed you tried again so the bugfix might have been pushed out to OpenShift already. Not too sure about that.Nice to see a fellow stringer user here. :)
I have a cronjob running in Openshift which was fine until some days ago, now all of a sudden it stopped working. This is the script: fetch_feeds. /usr/bin/rhcsh pushd ${OPENSHIFT_REPO_DIR} > /dev/null bundle exec rake fetch_feeds RACK_ENV="production" popd > /dev/nullExecute bit is set. It worked the whole time, I did not push updates to the app. I can login via ssh and execute it manuallycd app-root/repo/.openshift/cron/hourly/ sh ./fetch_feedsLogs say/var/lib/openshift/xxxxxx/app-root/runtime/repo//.openshift/cron/hourly/fetch_feeds: line 3: bundle: No such file or directorybut if I cd into the directory and executebundleit works. Force-stopping and starting the app did not work. I don't want to recreate the app because I will lose some settings. Any idea what else I can do? Thanks!EDIT: Deleting and re-adding the cron-cartridge did not change anything.EDIT2: Rebuild the application from scratch with the same instructions, it works. Seems like some update to the Openshift Platform borked something in my app. I still would like to know what happened but I don't know where to look at.
Cronjob in Openshift stopped working
There shouldn't be any space between the-pand yourpassword.For example, this is correct:-pPASSWORDThis is wrong-p PASSWORDAnd you are doing:-p ".$dbpass." ^ space here
I am trying to run amysqldumpusing acronjob. I get the following error:Enter password: mysqldump: Got error: 1045: Access denied for user 'user_name'@'localhost' (using password: NO) when trying to connectHere is the line of code trying to connect:$command = "mysqldump --opt -h ".$dbhost." -u ".$dbuser." -p ".$dbpass." ".$dbname." | gzip > ".$backup_file; system($command);Why is it saying (using password: NO)?
cron mysqldump saying not using password
Your cron job isn't set to run every two minutes, it's set to run on the second minute of every hour. You might change it as follows:*/2 * * * * /home/yuri/connector.sh >> /home/yuri/test.txt 2>&1
At first, this is not exactly a programming question and more specific to Linux. I hope that it can be answered here though.I have created a cron job which will execute a shell script every 2 minutes on my machine. However, the cronjob is not executing.output of crontab -e command2 * * * * /home/yuri/connector.sh >> /home/yuri/test.txt 2>&1I have the cron daemon running:ps aux | grep cron root 944 0.0 0.0 19120 932 ? Ss 08:25 0:02 cron 1000 19619 0.0 0.0 13600 880 pts/2 S+ 21:50 0:00 grep --color=auto cronThe connector.sh shell script runs properly when I execute it manually, however when run through the cron job created above, it does not work.I have redirected the output to a text file to know if something is going wrong while executing the cron job, but no such text file is created.
Cron job is not running on Linux
You should have a single Cron job that runs once, and loops through the 50,000 customers.What I generally do is pick one from the database, process it, mark it as done, then move on to the next one. I make my loop drop out after running for more than 170 seconds, and set a Cron job to run every 3 minutes for the whole month - it'll get through them as it can.
I have to setup a recurring invoice system for my boss and our system is built with php on a centos linux server. We have about 50,000 customers who we invoice every month, my job is to build a way to process the invoice script for all 50,000 customers each week, so the script will create a new invoice and do an insert query into the invoices table in our mysql database.My concern is if 50,000 seperate cron jobs ran every week will result in too heavy a load for our server, and what kind of limit crontab is able to handle before causing performance problems?Also important to note that the crontab file will need to be edited via a php script very often for editing and/or deleting individual invoices/cronjobs.Basically is this the best route to go?
Are Cron Jobs Practical When Dealing With > 190,000 Monthly Tasks?
This is becausecronhas its ownPATHvariable and doesn't use the same path that you do.For that reason, it would be advisable to call any programs that you use (especially through python'ssubprocess) with an absolute path to the executableYou could dowhich modprobeon the commandline to find wheremodprobelives (probably in/bin/), and then change your call insubprocess.pytosubprocess.call(['/bin/modprobe', 'w1-gpio'])
I have a python script that will read the temperature of from a probe on the GPIO pins of a Raspberry-Pi, and will append that temperature to a log file. Running the script form terminal with sudo permissions works fine:sudo python /home/pi/temp.pyI've attempted to run the script every 15 minutes from sudo's crontab file with the line:*/15 * * * * python /home/pi/temp.pyThis fails, with the output beingTraceback (most recent call last): File "/home/pi/temp.py", line 8, in <module> subprocess.call(['modprobe', 'w1-gpio']) File "/usr/lib/python2.7/subprocess.py", line 493, in call return Popen(*popenargs, **kwargs).wait() File "/usr/lib/python2.7/subprocess.py", line 679, in __init__ errread, errwrite) File "/usr/lib/python2.7/subprocess.py", line 1249, in _execute_child raise child_exception OSError: [Errno 2] No such file or directoryI know the issue is with the modprobe subprocess call, but I can't identify what exactly. In my script, I have the following code related to the issue:import subprocess subprocess.call(['modprobe', 'w1-gpio']) subprocess.call(['modprobe', 'w1-therm'])
Cannot run Python from Cron
* * * * your-script.phpYou will need to set up an internal script to call the outbound URL for processing.PHP example:<?php // your-script.php $ch = curl_init(); $timeout = 5; curl_setopt($ch, CURLOPT_URL, 'http://dvcticker.bugs3.com/json-data.php'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); $data = curl_exec($ch); curl_close($ch); // connect to database and save $data to your table ?>Bookmark this url. It is a cron tab generator. very useful.http://cron.nmonitoring.com/cron-generator.html
I would like to create a cron job which saves json data from an external url, hourly, to a mysql database. (http://dvcticker.bugs3.com/json-data.php)I'm new to cron, so this is pretty much all I have:0 * * * *Sorry for my limited knowledge and thanks in advance for answering.
Hourly cron job to save json data
If it's taking the input from stdin, make another script that will call your script with a pipe or a redirect.#!/bin/sh /foo/bar/my_command < my_inputYou can also launch it as a shell command in your crontab:0 * * * * /bin/sh -c "/foo/bar/my_command < my_input"
I have a run a script in cronjob. But that script is taking some user input.How can I handle such case?
How to give user input in cronjob script
If you want the job to run every 10 minutes between 09:00 and 17:00 then the cron expression should look like this:0 0/10 9-17 ? * MON-FRIThere's some great documentation on the Quartz site:http://quartz-scheduler.org/documentation/quartz-2.x/tutorials/crontrigger
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Closed10 years ago.Questions asking for code mustdemonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and theexpectedresults. See also:Stack Overflow question checklistQuestions concerning problems with code you've written mustdescribe the specific problem— andinclude valid codeto reproduce it — in the question itself. SeeSSCCE.orgfor guidance.Improve this questionI am using spring quartz. I need to run the jobevery 10minsfromMon 9:00AM To Fri 5:00PM.It means job should start at 9 AM on monday and it should continue to run every 10 mins till 5PM Friday.Could you please help me how can i write acron expressionfor above time period?Thanks!
complex cron expression to run the quartz job? [closed]
Here is the solutionhttp://www.magentocommerce.com/boards/viewthread/609113/#t462030I have the same problem, after I upgrade to 1.8.0.0 my cron is dead.Edit file cron.phpAfter$isShellDisabled = (stripos(PHP_OS, ‘win’) === false) ? $isShellDisabled : true;around #47 add this line of code$isShellDisabled = true;
I've just upgraded my magento install with version 1.8.0.0 fron magento connect.I’ve upgraded magento to 1.8.0.0 using “Magento connect” and since then the following message appearedCronjob status: Cron.php doesn’t seem to be set up properly. Cron did not execute within the last 15 minutes. Please make sure to set up the cronjob as explained here and check the cron status 15 minutes after setting up the cronjob properly again.All scheduled jobs (stock import/order export, log cleaning, ...) have stopped since the upgrade.my crontab is:$ crontab -l */5 * * * * wget -O /dev/null -q http://localhost/cron.php > /dev/nulland manually executing wget from a shellwget -O /dev/null -q -S http://localhost/cron.php HTTP/1.1 200 OK Date: Thu, 26 Sep 2013 07:10:10 GMT Server: Apache X-Powered-By: PHP/5.3.21 ZendServer/5.0 Vary: Accept-Encoding Keep-Alive: timeout=5, max=99 Connection: Keep-Alive Transfer-Encoding: chunked Content-Type: text/htmlI've installed Aoe scheduler which shows a long list of pending jobsNo errors anywhere (apache logs, magento logs, ...)How can I resolve this?Thank you.UPDATE: calling the shell script re-activated the hearthbeat ... still I cannot understand where the problem is*/5 * * * * /var/www/magento/htdocs/cron.sh > /dev/null
Magento 1.8.x cron stopped
That's probably an indicator that mysql is failing to run as specified.Redirect standard error when you run the command, and you'll at least get an e-mail with the error message telling you what you're missing:mysql 2>&1 -u root -p -e 'select count(*) User_Count from ' | mail -s 'Count' "email_id"Also, make sure the directory where mysql resides is either in the PATH, or you specify it manually on the command line.
I have following command in Ubuntu Linux,mysql -u root -p"password" "dbname" -e 'select count(*) User_Count from "tableName"' | mail-s 'Count' "email_id"When this command is executed from command line it send mail with subject and query output as message bodyHowever if I schedule the same command through crontab - I get email only with subject and message body is empty
email body content gets removed when mail sent from crontab
Cron doesn't have it's PATH set. The easiest thing is to change the php command to the full path of the php binary./usr/bin/php /path/to/yourscript.phpI'm fairly certain that's the path in CentOS but you can know for sure by doingwhich phpon the command line and it will tell you.
I have searched hell and high water for a solution to a problem I'm having in CentOS. I'm trying to set up a cron job that executes a PHP script. I was able to get this working usingwget, but now that we are going into production, I need to find a way to do this whilst being more secure, as the cron job itself works with sensitive data.The error that I'm getting is:-bash: php: command not found.Now I've looked around and I've seen people having the same problem, but nothing has been able to help me get this working.For reference, here is what the working crontab looked like using thewgetcommand.* * * * * wgethttp://www.domain.com/cron_script.phpThis is working fine, but I need to translate this into executing via PHP, rather than making an HTTP request to get the job done.Let me know if I left anything out.
Setting Up Crontab to Execute a PHP Script in CentOS
the problem is the SHELL. You can solve this problem via two ways:1] I simply changed the sentence: SHELL="/usr/local/cpanel/bin/jailshell" in /var/spool/cron/account to SHELL="/bin/bash"2] You can copy file /etc/lynx.lss to directory: /home/virtfs/account/etcBoth worked for me !Wilhelm
using cpanel server, setting a simple "lynxhttp://www.domain.com/script.php" command gives following error and I am unable to understand it.Lynx file "/etc/lynx.lss" is not available.
Lynx file "/etc/lynx.lss" is not available
Depending on the query, if it's SQL related only, consider aMySQL event. But it depends on what it does. If PHP code is required to interact with it... events won't help. If it just does some updates in MySQL(like expired user sessions and removing unconfirmed user accounts)... an event will do.Running every minute is not hard on the server, it depends on what it does.microtime()execution of the script and log it to a text file withregister_shutdown_function()(you can alsomemory_get_peak_usage()).See how long it takes, how much memory it consumes... that will tell you how hard it is on the server.
I have a cron job running that executes a PHP file which checks a MySQL database for a change. I have this script running every minute but it's very simply query.Still, is running a cron job like this every minute going to be too hard on the server? Is there a better approach to what I'm doing?
Cron job every minute?
Have never used it butCronExpressionDescriptorseems to be what you're looking for,click here to see a live demo.CronExpressionDescriptor on GitHubCronExpressionDescriptor on NuGet
I'm using Ncrontab in a C# web application. Currently, I have a view with a series of textboxes, checkboxes, and drop downs to create a crontab schedule. However, what I need to be able to do, for the purposes of allowing the user to edit their schedule, is take a crontab string and fill out the view appropriately.Take this string for example:0 */4 * * *I need to be able to break that down, select 'Hourly' from a drop down, and fill in '4' in the a textbox (occurs every 'x' hours). In other words, I need to be able to do the opposite of whatcronmakerdoes.I've been poking around Google and the likes, and seen a few references to Quartz.NET, but I'm not sure that has the functionality that I need. Any suggestions?edit: I suppose I'm asking if there's a more efficient way to do this without a bunch of conditionals and string comparisons. Is there a library I should know about, or should I just roll up my sleeves and start parsing?
Reverse engineering Crontab string
Depending on how loosely you might want to enforce those 5 minutes, and if you have regular traffic to your site (at least 1 request once a minute), you can consider:on each request check the database when the job ran last timeif this is more than 5 minutes ago, run the job and update the databasethe more this script is run, the more accurate your 5 minutes will be. To increase the times this script is run:see if there is some file that is included on every request, like a config.php.Or maybe you have some routing, eg all requests go through index.php
Ok so, I have a web server and a site that uses php. My question is how do I trigger php files to run at regular intervals (say every 5 minutes for example)?Unfortunately my web hosting provider does not seem to support cronjobs, but surely there must be some alternative for people without cron access?
Trigger php file at regular time intervals - without cronjobs?
You forgot to call.build();method on theTriggerBuilder. The code should look like this:newTrigger().withSchedule( DailyTimeIntervalScheduleBuilder.dailyTimeIntervalSchedule() .startingDailyAt(new TimeOfDay(8,0)) .endingDailyAt(new TimeOfDay(11,0)) .withInterval(1, IntervalUnit.DAY)) .build();
I have created one scheduler :SchedulerFactory sf = new StdSchedulerFactory(); Scheduler sched = sf.getScheduler(); Trigger trigger1 = (Trigger) newTrigger().withSchedule(DailyTimeIntervalScheduleBuilder.dailyTimeIntervalSchedule().startingDailyAt(new TimeOfDay(8,0)).endingDailyAt(new TimeOfDay(11,0)).withInterval(1, IntervalUnit.DAY)); Date ft = sched.scheduleJob(job, trigger1);But it is throwing an Exception :Exception in thread "main" java.lang.ClassCastException: org.quartz.TriggerBuilder cannot be cast to org.quartz.TriggerHow can i fix this error?
Quartz scheduler is not working
Put it outside of yourpublic_htmldirectory. If it's not served, nobody can trigger it with a browser.
So i have a cron job that does a lot of stuff(irrelevant for us now).I've set the file permission to 744 in hope that it will prevent browser execution of the script.ideally i would like it to be set so only the server user //cronjob can run the script and not people through their browser which could lead to a lot of problems.here is how I've set the cron job:/usr/local/bin/php /home/xxxx/public_html/cron/scriptName.php >[email protected]`Could anyone point me to the right direction regarding this issue ?
Trying to prevent browser trigger of a cronjob
You have to put an absolute path for log.txt. Otherwise, it will be created in /.Also,>/dev/null 2>&1has to be at the end of the sentence. If you want the 2 (meaning the errors) to be dismissed, just write2>/dev/null.Then, your final cronjob would be like this:* * * * * /usr/bin/ls pathToRandomDirectory > /pathToRandomDirectory/log.txt 2>/dev/null
I'm trying to create a simple crontab that creates a file called log.txt every minute by populating it with a simple command's output. Right now this is what I've put into my crontab:* * * * * (/usr/bin/ls <pathToRandomDirectory) > log.txtBy my understanding, the 5 asterisks correspond to "every minute". But when I run this the log.txt file is not being created. Is there something I'm missing here?ALSO, if I didn't want to have an email sent to me whenever the job is created I found that I need to put the line:>/dev/null 2>&1Somewhere in my crontab file. Where exactly does this go? At the end of the command or on a separate line?
Crontab to create a new file
UsecURLto request a copy of the page.Check the HTTP status returned with$http_status = curl_getinfo($http, CURLINFO_HTTP_CODE);If it's anything other than 200 send yourself an alert.As for how to send an SMS, pretty much all mobile providers have an email domain that you can use to send an SMS to your phone, ie:[email protected]
I am trying to figure out a php script to check a bunch of links from a separate text file and if anyone of them is showing 404 then the script should trigger a php file, which will send sms notification. I already have sms file ready and just need to trigger it.For example, there are several links in links.txt (which is also uploaded on the server), such ashttp://example.com/link1 http://example.com/link2 http://example.com/link3These links are not necessarily offline, they may be redirecting to a non-existent page, while the main site is alive.If example.com/link1 is down smsnotice1.php should be triggered If example.com/link2 is down smsnotice2.php should be triggered If example.com/link3 is down smsnotice3.php should be triggeredThe reference to smsnotice1.php, smsnotice2.php, smsnotice3.php can be either in the main script or another php file.If none of the links is down, then no notice should be sent.I can run this script from a php server on a cron for frequent check. Thank you very much for the help!
Check if links are 404 and if so, then send sms
Undercron, there is no guarantee that your environment variables (most importantlyPATH) will be set proprerly.Try adding line like this at the top of your crontab:PATH=/bin:/usr/bin:/sbin:/usr/sbin:/usr/local/binAlso, it would be good idea to use full path for mkdir:mkdir /path/to/my/dirAlso, it would not hurt to make sure that your cront.sh is executable:chmod +x /home/rishi/cront.shAfter that, it should work.EDITGeneric method to debug crontab issues:At the top of your script to debug, add a line:set # this should print all environment variablesExecute your script manually, redirect output to some log file1.Now, edit crontab to be something like this:* * * * * /path/to/my/script 2>&1 > /path/to/log/file2Be sure that log file will be writable for your script. Also, be sure that your script has executable bit set.Compare log file1 and log file2, paying close attention to env. variables. If they differ, use whatever method you want to set them to be the same. It could be adding lines tocrontab, or usingexport var=valuein your scripts.After that, there is no reason for this to not work properly.
This is the content of my crontab -e file#!/bin/bash 6 14 * * * /home/rishi/cront.shAlso, the cront.sh file has only thismkdir fooI have been trying to make this work since the last 2 days. The cront.sh command works when ran from the terminal. But, does not work from crontab.EDITIt turned out that just editing the crontab -e using root did the job. Nothing more had to be done.
Cron Jobs not running in Linux Mint 12
In your CRONTAB, you'll want to run update.php. Javascript/jQuery is run client-side. When setting up a CRON Job, you are running a command on the server, in this case, a PHP script. As such, only the PHP will run.An example entry in CRONTAB:*/1 * * * * php /path/to/update.phpThis will run the commandphpeveryminute, passing itupdate.phpas an argument.More information about CRON format:http://www.nncron.ru/help/EN/working/cron-format.htm
I have this jquery code:<script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> setInterval( function (){ $.get('update.php',function (){ }); },1000 ); </script>It calls my update.php file every second which updates the database. This works without any problem when I manually run it on the browser but it doesn't work through CRON. What can I do to make it work through CRON jobs?
works in browser but not through CRON. Why?
You are using the & sign in the command line, so the parameter t gets lost and your script does not get all its input data (and it's probably the same with your cron job, since it's executed shell-wise).try:curl 'url'Checkouthttp://linuxcommand.org/lts0080.php, search for "Putting a program in the background" for more info on & in the shell.
I am trying to figure out why my curl cron job is not executing correctly. When I run it in the browser it runs just fine however if I run it in command line I get the following output. I have replaced the actual URL however the url is something likeexample.com/file.php?pass=password&t=droot@low [/home/user]# sudo -u user curl URL[1] 13959 root@low[/home/user]# Starting backups for0accounts!The output in the browser runs for all 9, 10, or however many backups I have. Am I just missing a flag in my curl request?
Why is my curl cron job not running?
You should use an absolute path instead of../copias/fichero....You don't know what the current directory will be when the command is run by cron.
I have crontab :35 16 * * * mysqldump -h mysql2.alwaysdata.com -u user -ppass --all-databases > ../copias/fichero_`date +%d-%m-%Y-%H:%M:%S`.sqlbut the command working correctly without crontab. the folderchmod 777 -R.Thanks.
crontab no working
The gemwheneveruses thecrontab [CRONTAB FILE]to write it's crontabs. If configured to setup the crontab for another user it usescrontab -u [USER] [CRONTAB FILE]. The following excerpt fromlib/whenever/command_line.rbdisplays how the command is generated.def write_crontab(contents) … command = ['crontab'] command << "-u #{@options[:user]}" if @options[:user] command << tmp_cron_file … endSo if the user account which executes thewhenevercommand isn't able to execute the commands listed above, I'm pretty surewheneverhas no way to work as expected.The user option can be given like this:whenever --user someone.
I'm about to write a script which execute some ruby scripts in a scheduled manner. Production env: Enterprise's cluster running debian with restricted permissions for users so I don't have permissions to edit cron table files. can I use whenever ruby gem? ruby 1.9.1 Thank you for your answers.
Is it possible to use the 'whenever' ruby gem while not having permission to use crontab?
*.phpis regular script file which, as any other scripting languages like i.e. perl requires interpreter to run. So if you want to run your script from command line you have either call interpreter and give it your script file as argument, like:$ /usr/bin/php myscript.phpAnd that's it - it should run.Or (if working using linux/bsd) addas very first line of your PHP script file:#!/usr/bin/php -qwhich tells shell, where to look for interpreter for this script file. Please ensure your PHP is in/usr/binfolder as this may vary depending on the distro. You can check this usingwhich, like this:$ which php /usr/bin/phpif path is right, you yet need to set executable bit on script file so you'd be able to try to "launch it":chmod a+x myscript.phpThis will make it behave as any other app, so you'd be able to launch it this way:/full/path/to/myscript.phpor from current folder:./myscript.phpAnd that's it for that approach. It should run.So your crontab line would look (depending on the choosen approach):1 * * * * /full/path/to/myscript.phpor1 * * * * /usr/bin/php -q /full/path/to/myscript.phpAnd you should rather use "0" not "1", as 1st minute in hour is zero, i.e.:0 * * * * /usr/bin/php -q /full/path/to/myscript.phpEDITPlease note cronworking directoryis user's home directory. So you need to put that into consideration, which usually means using absolute pathes. Alternatively you'd prepend your call withcd <script working path> && /usr/bin/php -q /full/....
Ok I have been looking into cron jobs for hours, checked every post here, looked in google but I just do not understand how it works.I have set up a cron job using my path1 * * * * /home/myuser/domains/mysite/public_html/live.phpI have also tried/home/myuser/public_html/live.phpNothing seems to be working.Do I have to add something in the php file (live.php)? That is the code that has to be executed. The code itself works.I know you will all think that I am lazy but I really can't figure this out.
what to change in my php script for the cron job to work
Why can't you use wait in your script when under crontab? In my case, it can.With a file named 1.sh as below:#!/bin/bash exec 2>&1 sleep 20& time wait echo helloand a task in crontab as below:* * * * * bash ~/1.sh > ~/1.txtIt can be shown the wait is working because it cost 20 seconds executing:$cat ~/.logs/1.txt real 0m20.001s user 0m0.000s sys 0m0.000s helloNow perhaps you can try to debug why wait don't work in your crontab. Are you sure you are using bash instead of another shell like POSIX sh? The behavior can be different.And if you can't getwaitworking, you can tryflock.
I have this piece of code:sqlplus usr1/pw1@DB1 @$DIR/a.sql $1 & sqlplus usr2/pw2@DB2 @$DIR/b.sql $1 & wait echo "Done!"Both sqlplus sessions in the background so they can run at the same time, and wait command to wait until both of them finish.In the real program, the "echo" is actually a call to another program that works on spooled files by the previously executed queries, hence the importance to wait for both of them to finish.I have a problem since it works fine when I execute it by myself, but it doesn't when I schedule it on crontab. Since I can't seem to find the solution, I would like to somehow simulate that behavior. This is my idea:sqlplus usr1/pw1@DB1 @$DIR/a.sql $1 session1=$! //I think this stores sqlpluss pid sqlplus usr2/pw2@DB2 @$DIR/b.sql $1 session2=$! while (not finished($session1) and not finished($session2)) //pseudocode do nothing //maybe sleep for a few seconds, something that wont waste resources unnecesarally echo "Done!"I need some help on how to complete that loop. First of all, I'm assuming $session1 and $session2 have the pid of each sqlplus session. Not really sure if that's correct. Then, there must be some easy way of checking if the process is still running, having it's pid. At last, if still either one is running, I want to just wait but not looping millions of times, but maybe sleeping for a minute:Thanks in advance for any suggestion!
How to wait for background jobs to finish in shell
There isimport. Read uphere. Example:import -window root -delay 200 screenshot.pngyou can write a script to randomize.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed11 years ago.I want automatic screenshots to be taken at random times throughout the day, preferably say 30 screenshots scheduled for independent random times.This is so I can get a sort of representative sample of how I spend my time, and also to show other people, as a way of boosting my motivation to actually do useful stuff. I want the times to be random so that I don't look at the time and only start doing useful stuff right before the screenshot is to be taken; it'll be like a boss checking in on me unexpectedly. I also want some sort of notification right after a screenshot's been taken.I'm on a standrad Ubuntu laptop. My problem: I am not sufficiently versed in cron-fu to figure out how to make it schedule tasks at random times. I also don't know how to do notifications from the command line.This all seems like a pretty hard problem to me. Can any of you help?
Linux: Take automatic screenshots at random times [closed]
Say you want to run a job every night at 10pm then the crontab would look like:00 10 * * * (cd /e/m/user/testing3/kaboom ; ./kaboom testlis ) > /tmp/cronjob.log 2>&1Crontab entry just contains the commands you want to execute.For examples on timings please check thisgeekStuff link.
I run a list of tests using this command: "./kaboom testlist" which is written in Python.This command can only be excuted in the directory /e/m/user/testing3/kaboomI want to run this command every night at midnight using a cronjob. The only examples I've found online are prewritten shell scripts. So, I am not sure how to format this into a crontab so that it does what I want.Any suggestions?
How do I execute this command using crontab?
Add asleep 5orsleep 10to the start of the cron entry.
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Closed9 years ago.This question does not appear to be abouta specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic onanother Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.This question does not appear to be about programming within the scope defined in thehelp center.Improve this questionIs it possible to have two linux users with slight delays on their clocks?The reason I ask is I have two scripts executed by the cron every minute (one on each user). One script copies a file from the another machine the other loads the data in the file into mysql.We have been finding the loading of the data misses the first minute 90% of the time. I think this is because it is called exactly the same time as the call to copy the file from the other machine is executed.If I could delay the user clock whose cron executes the loading script by 5 seconds i think this would solve the problem.Perhaps there is another way of achieving this? Something easier I am missing. I would like the first script to be called every round minute and the second to be called 5seconds after every round minute.
Two linux users with different clocks [closed]
The problem here is that you use bash-syntax, and the script (when it is executed from cron) is interpreted by/bin/sh(that known nothing about arrays and the()construction.).You must either specifybashas an interpreter of the script using she-bang notation:#!/bin/bashor run the script explicitly withbashfrom cron:bash /path/to/scriptor rewrite script so, that it could run without arrays.
i have got a bash file which i want to toggle via the sudo crontab list. Problem is, that it does not work, because when i run the script with sudo, there is a syntax error message on this line:size=(`du -h $backupDir --summarize`)If i run the same script without, i have to type the sudo pw, but it works without any problems. I allready tried a few variations with brackets, with or without backticks, with or without spaces, etc but nothing helped. The error message is:Syntax error: "(" unexpected (expecting ";;")Any help?
sudo bashfile makes syntax error
You can try this:wget http://localhost/index.php/cron/resetViewsBasically, since you have the capability to use wget that will definitely call the controller method, why use cli?EDIT:referring tothis, perhaps you should do acdcommand to the directory and then call index.php. Worth a try because if ci was trying to load controller from path relative to the cron's pwd, then it might throw a 404. right?
I have a cron job which needs running on my site. I have set up the model and controller, then set the following cron job to run every hour:/usr/bin/php /path/to/directory/index.php cron resetViews;I have the URI_PROTOCOL index of $config in my config.php file is set to AUTO and there are no spelling errors.When I run the command, I get the4 html of my home page, which is also my default controller. Any ideas?EditI have changed the command to:cd /path/to/directory; /usr/bin/php index.php cron resetViews;and now I get the following error on top of a printout of my home page:PHP: Error parsing /home/crowston/public_html/2012/php.ini on line 1Here is my entire php.ini file:error_reporting(E_ALL); ini_set('display_errors', 'On');I have also tried with a blank php.ini fie to no avail.The php.ini file has caused no errors throughout the entire construction of the site :S
Codeigniter cron job issue
because you are trying to run abashfile through python!error:python test.shyou should insteadbash test.sh
I had created a python script for exampletest.pyand path of the file is/Desktop/test.pyi want to run the file using cron jobs, so decided to create a bash script with nametest.shwith the code belowtest.sh:#!/bin/bash cd /Desktop/test.py python test.py 2>log.txtbut this not working, when i tried to test it like below i am getting error as given belowsh-4.2$ python test.sh File "test.sh", line 4 python test.py 2>log.txt ^ SyntaxError: invalid syntaxIf this works fine then i can open cron tab withcrontab -eand can execute with the following command/2 * * * * /path/to/bashscript/test.shCan anyone make this work will appreciated.........
bash file is not working for executing python file on fedora
You can use a cron (ran every minute) to set a status field on the thread table to closed such as.UPDATE threads SET status='closed' WHERE lastPost+INTERVAL 3 DAY<NOW()Then in PHP something such asif($thread['status'] == 'closed') { // Put your HTML here. }
Lets say there is a thread ( on forums ) which will be active for 3 days only. Now, after 3 days, I want this thread automatically closed.Can I use reference to time when this thread is created in database, and than makeifstatement if current date + days is bigger than date created, I will print out"<h2>Thread Closed for posting</h2>"And when I consider some other tasks, I suppose I can use reference to time and have certain event executed on this.Am I right?
When do I need to use cron?
For every even hour, it will run at :00 and :30 - every day of the week.E.g., 0:00, 0:30, 2:00, 2:30...12:00, 12:30, 14:00, 14:30...22:00, 22:30
I have a cron job with the following expression:*/30 */2 * * *Would this run every half hour AND every 2 hours or will it run every 2.5 hours?
What is the schedule on this Cron?
Set the cron tab using php -n [path_to_your_script]flag 'n' tells php to ignore the php.ini file settings.
I have a PHP script running every hour or so. The script does a long process which is expected to be more than 2 hours. But my PHP is timing out every 60 seconds. I have usedset_time_limit(0);but this is not allowed in safe mode i guess. So could you guys please tell me how to have infinite execution time without really changing the safe mode settings ?
Dealing with PHP timeouts in Cron when PHP is in safe mode
Are all the directories in the path set to at least +x for the user executing the cron job? If you can't at least execute the directories abovecake, you won't be able to execute the program.
I am getting this error when I try to run a CakePHP 2.1 Shell from a cron job:/bin/sh: /home/[other-folders]/lib/Cake/Console/cake: Permission deniedThis is the code I've been using for almost a year with CakePHP 1.3.7 and it worked well. What could the problem be? I've checked the permissions on thecakefile, and it is 755, just like thecakefile I had in 1.3.7. Thanks!
CakePHP 2.1 Permission denied on cron job
Did you put something like#!/usr/bin/phpin front of your PHP file? The error seems to sayshwas used to run your PHP file, and it absolutely failed.
I have set up a cron job in cpanel in a standard way. I am trying to run a php file, when the email is delivered it gives me errors:/home/shoes/public_html/webPages/products/time.php: line 1: syntax error near unexpected token `(' /home/shoes/public_html/webPages/products/time.php: line 1: `<?php include ('../../database/config.php'); ?>How can I get this php script running perfectly? As when I load this using browser it gives out the actual result but not in cron.
Cron job is not working
It's probably producing too much output. This really isn't a bug, but a feature as cron typically send emails with it's output. MTA's don't like text messages with many many lines, so cron just quits. Maybe the silent quit is a bug though.You could also use ln -f to suppress the ln errors in only the case of pre-existing files.
Here is a snippet from a script which I generally execute from cron:if [ "$RESCAN_COMMAND" = "wipecache" ]; then log "Linking cover art." find $FLAC_DIR -name "*.jpg" | while read f; do c=`echo $f | sed -e 's/flac/mp3/g'`; ln -s "$f" "$c"; done log "Done linking cover art" fiThe script works perfectly when run from the command line. But when run by cron (as the same user) it fails somewhere in thefindline. The "Done" message is not logged and the script does not continue beyond theifblock.Thefindline creates links from files likeflac/Artist/Album/cover.jpgtomp3/Artist/Album/cover.jpg. There are a few hundred files to link. The command generates a lot of output tostderr, because most, if not all, of the links already exist.On a hunch, I tried redirecting thestderrof thelncommand to/dev/null:find $FLAC_DIR -name "*.jpg" | while read f; do c=`echo $f | sed -e 's/flac/mp3/g'`; ln -s "$f" "$c" 2>/dev/null; doneWith that change, the script executes successfully from cron (as well as from the command line).I would be interested to understand why.
Why does part of a script executed by cron fail unless stderr is directed to /dev/null?
Have a look at this. Should answer your questionWhere can I set environment variables that crontab will use?Again read thishttp://linuxshellaccount.blogspot.com/2007/10/crontab-and-your-environment.html\The easiest way you can make sure that you have same environment in cron as you have when running any script as the regular user is to "source" the environment into the script by adding a line like:. /etc/profile . /home/user/.profileto the top of your script (below the #! line). The literal dot, space, filename patterns tells your shell to read in all variables in that named file, so you could run your cron job with the same environment as when you test it manually, which might avoid issues caused by points 1 and 2 above.
testjob.sh#!/bin/bash export JAVA_HOME=/usr/java/jdk1.6.0_07 echo "Java Home is $JAVA_HOME" export CLASSPATH=.:..:$CLASSPATH: echo "Path is is $PATH" echo "CLASSPATH is is $CLASSPATH" $JAVA_HOME/bin/java TestJob echo "$JAVA_HOME/bin/java TestJob"crontab -e* * * * * /usr/testjob.sh >> /usr/result.txt 2>&1if i run shell script manually it runs fine but when it will run through crontab job, error will occur as class not found..please suggest..
crontab doesnt work for run java class
Check yourLD_LIBRARY_PATHenvironment variable?
I am running a bash script that uses libboost to hold a statistical model in memory. When I run the script directly from the command line (ie: # /pylda/exec-test.sh) it works fine. However, when it runs on the cron job, I get the following error:"/root/pylda/src/infer: error while loading shared libraries: libboost_program_options.so.1.46.1: cannot open shared object file: No such file or directory"How does cron behave differently? Is there an environmental variable that needs to be set? This is cron as root, as far as I know.Thanks
Bash script failing when run via cron, can't find Libboost library
If you place your php script outside of your web directory, only you / cron will be able to run it and nobody else.There are different ways to run a php script from cron, like for example adding something like this as the first line of your php script:#!/usr/local/bin/php /* depends on your server and configuration */
I have a cron job that runs several times a day at full hours (:00). How can I only allow the PHP scripts to run during this time? I don't want someone else to be able to run my script. Here's what I thought of:if (date('i', time()) > 2 || date('i', time()) < 58) { die; }Are there better, more secure ways?
How can I only allow cron to be run on a PHP file during a certain time
bundlewill have to be in that subshell's path. Try specifying a full-blown/usr/bin/bundle(or whatever it is).
On Redhat, using Whenever. My cron jobs fail to run hourly. I need help as to why.Schedule.rbevery 1.hours do rake "deathburrito:all", :environment => "development" rake "bamboo:all", :environment => "development" rake "jira:grab_data", :environment => "development" endCrontab -l0 * * * * /bin/bash -l -c 'cd /var/www/qadashboard && RAILS_ENV=production bundle exec rake deathburrito:all --silent' 0 * * * * /bin/bash -l -c 'cd /var/www/qadashboard && RAILS_ENV=development bundle exec rake bamboo:all --silent' 0 * * * * /bin/bash -l -c 'cd /var/www/qadashboard && RAILS_ENV=development bundle exec rake jira:grab_data --silent'Can anyone help me? I am not even sure what else I should be checking.
Rails hourly cron jobs using Whenever fails to run hourly
The environment variables for a cronjob are significantly reduced from your login; you'll want to set $PATH for your crontab.For instance:PATH=$HOME/bin:$PATH @daily $HOME/backup_scriptYou may want to runwhich herokuto figure out what path you need to add.
I run these three commands everyday:cd /Users/xxx/code heroku pgbackups:capture --expire curl -o latest.dump `heroku pgbackups:url`So I thought I'd try to move it into a cron job so I created a file called /Users/xxx/code/backup_script that has the following:cd /Users/xxx/code heroku pgbackups:capture --expire curl -o latest.dump `heroku pgbackups:url`However, when I run ./backup_script it gives this error:./backup_script ./backup_script: line 2: heroku: command not found ./backup_script: line 3: heroku: command not found curl: no URL specified! curl: try 'curl --help' or 'curl --manual' for more informationI'm a unix newbie - can someone help me figure out how to fix the script above?
unable to get cron script to work
To have a portable solution you can useenv:*/5 * * * * /usr/bin/env php /home/..app/webroot/cron_dispatcher.php /devices/checkForAlert
I am setting my cronjob as:*/5 * * * * /usr/local/lib/php /home/..app/webroot/cron_dispatcher.php /devices/checkForAlertwhereas in checkForAlert function of devices controller i’ve just printed ‘hi’ but mail from cronjob only contains this/bin/sh: /usr/local/lib/php: is a directoryCan you please tell me that is going wrong here…
Cron doesn't find PHP
Yes, a cronjob is what you're looking for. Depending on your server OS flavor (I'm assuming linux), creating one is fairly easy. On a Debian system, you'd put your script file in/etc/cron.hourly/and it would be run once every hour.To create a php script that can be run from the command line, follow this format:#!/usr/bin/env php <?php // do stuff... ?>And don't forget tochmod +xthe script.
I have a php/mysql question:I am designing a website that takes xml feeds and puts them into a mysql table. From that table, I want mysql to take this new information and perform a series of calculations which then changes fields in another part of the database. This newly updated information is then displayed on the website.I understand how to:convert from xml to phpplace these variables into mysqlcalculate the new info (in theory with php)What I don't get is: where do I put the php script that tells mysql to do the calculations and what the calculations actually are.Does it just go in a php file on the database that gets called by a cron job? I have no idea how to do linux commands though I suppose I could learn if needed. Is there any other way to simply put a script on a server and have it called every hour or so and it checks to see if any new tables have been added and if so, it does the calculations?
Automatic PHP scripts
Do the following:Add a date field to the record and make it unique.Modify your job to check if there is an record - if so, don't insert a new one.
my coding had regarding crontab in linux and php, what I want to do is my cronjob datetime is * * * * *, that mean it every minute also will checking the result, so once my result had check complete , it will insert to database, but now my results are keep inserting to database, so how to everyday insert only one record in database with the cronjob run every minute or how to stop keep inserting result to database?thank you hope you guys reply me soonest
How to insert only one record per day?
I have used a system that adapts the update frequency of the feed, described inthis answer.You can spare resources if you use conditional HTTP GET's to retrieve feeds that support it. Keep the values of theLast-ModifiedandETagheaders from the HTTP response. On the next try supply their values in theIf-Modified-SinceandIf-None-Matchrequest headers.Now if you receive the HTTP 304 response code you know the feed hasn't changed. In this case the complete feed hasn't been send again, only the header telling you there are no new posts. This reduces the bandwidth and data processing.
I am working on blog-aggregation project. One of the main tasks is the fetching of RSS feeds of blogs and processing them. I have currently about 500 blogs, but the number will be increasing steadily with time (it should reach thousands soon).Currently (still beta), I have cron job which periodically fetches all the RSS feeds once every day. But this puts all processing and network IO on only once per day.Should I:Keep the current situation (all at once)Make hourly fetching of number_of_blogs / 24 (constant cron job timing)Change cron periodicity to make constant number of RSS fetches (10 blogs every smaller time)or there any other ideas?I am on shared hosting, so reducing CPU and network IO is much appreciated :)
cron job periodicity and amount of work
Here is an example showing a cron which executes 3 scripts at 9am Mon-Fri.00 09 * * 1-5 script1.sh && script2.sh && script3.sh 2>&1 >> /var/tmp/cron.logIf any one of the scripts fails, the next script in the sequence will not be executed.
I would like to have a cron job which executes 3 shell scripts consecutively i.e., execution of next shell script depending on the completion of previous scripts. How can I do it?
Unix cron job for shell scripts
The first parameters to create a CronTrigger is never a cron expression but the trigger name.Instead you can use this overload:var trigger = new CronTrigger(triggerName, groupName, "0/30 * * * * ?");UPDATE:You canconfigurea logger which is used by Quartz.net to trap some internal error. I used NLog and it has helped me a lot to debug common mistakes.
i have a problem with using cron trigger in Quartz.net. My code:var trigger = new CronTrigger("0/30 * * * * ?"); trigger.Name = "some name"; trigger.Group = "group"; scheduler.ScheduleJob(jobDetails, trigger);it should run every 30 seconds, but on last line following exception occures: "Based on configured schedule, the given trigger will never fire." can anyone help?
quartz.net cron trigger
You seem confused aboutremoteandlocal.This would be running it locally:php test.phpThis would be an example of running it remotely with a cron:* * * * * curl --silent http://www.yoursite.com/cronjob/test.phpOf course this remote usage implies security implications that you'd need to address.
I have below scripts as php file and want to execute this in CRON. It works in local but when I go remote linux it fails.<?php $a = 1; $b = 2; $b = $a + $b; echo 'TEST-SUM'.$b; //echo substr("Hello world!",6); //echo 'Test Cron Job On Mturk!'; ?>1) The above one works in this way of execution in REMOTE server.php test.php2) But not using the following cron syntax:* * * * * php /home/www/cronjob/test.php 2>&1 >> /home/test/www/cronjob/createhitlog.logI am trying to check whether CRON is working on the REMOTE server or not.
Why my cron is not executed on the remote linux?
To find all snapshot files that were updated more than two weeks ago:find . -type f -mtime +14 | grep SNAPSHOTPipe that toxargs rmand you should be good.The one caveat: a repository manager will create ametadata.xmlfile that lists all published revisions. Assuming that you're just usingscpto publish, and a webserver to retrieve, I don't think that file exists (so the fact that this script doesn't touch it shouldn't be an issue).
So we have our own private Maven repository that we publish snapshot builds to.We have lots builds so diskspace is starting to become a problem for all our snapshot builds. While its fun and all to go manually do this I was wondering if anyone knows of a CRON script that I can run to do the snapshot cleanup.I know sonatype does this for their own repo but I could not find a script.
Looking for a Maven Repository Cleanup script (unix) for Snapshot builds (diskspace)
Sounds like you need a CMS, maybe likewordpress. You can schedule an item to publish in the future.
EDIT: I have already set up my website, so using a cms isn't really an option.Is there something that that is "rather" user friendly (as I do plan to use it quite often if there is such a thing) that will basically allow you to schedule a task of say, deleting the text "I am going camping tomorrow" and insert the text "I have gone camping" in between and the right after at a specific time. Of course the program would need to be able upload the file at that specific time as well. This program should also be able to insert a record into phpmyadmin at a specific time as well.I was going to look into Cron, but my host does not provide it. Should I switch host, or is there an alternative? Is Cron even capable of the thing I just described? If so would it be too complex (or not worth going thru the process everytime)? Is there another easier/better/alternative solution?All inputs would be greatly appreciated, thanks!
Is there a program/application that will easily allow me to update my site frequently?
There are a couple of problems with your script, I have altered it below, note carefully the change of spaces, spelling ofdateand replacement of|for;.The most interesting problem however is thatmailunfortunately can't send attachments. You could use uuencode to embed the file in the mail using:15 2 * * * root mysqldump -uroot -pPASSWORD --all-databases | gzip > /database_`date +'%m-%d-%Y'`.sql.gz ; uuencode /database_`date +'%m-%d-%Y'`.sql.gz /dev/stdout | mail -s "Report 05/06/07"[email protected]Or if you want to have a proper MIME attachment use (You will need MetaMail installed):15 2 * * * root mysqldump -uroot -pPASSWORD --all-databases | gzip > /database_`date +'%m-%d-%Y'`.sql.gz ; metasend -b -t[email protected]-s "Report 05/06/07" -m application/gzip -f /database_`date +'%m-%d-%Y'`.sql.gzOr as above with mpack installed, instead of MetaMail:15 2 * * * root mysqldump -uroot -pPASSWORD --all-databases | gzip > /database_`date +'%m-%d-%Y'`.sql.gz ; mpack -s "Report 05/06/07" -c application/gzip /database_`date +'%m-%d-%Y'`.sql.gz[email protected]
I would like to run a cron job to backup some mysql databases by piping the output to a file and then emailing it.Will the following work?15 2 * * * root mysqldump -u root -pPASSWORD --all-databases | \ gzip > /database_`data'+%m-%d-%Y'`.sql.gz | \ mail -s "Report 05/06/07"[email protected]< /database_`data'+%m-%d-%Y'`.sql.gz
Linux cron job to email output from a command
to run this cron every minute you have to use something like this:*/1 * * * * wgethttp://www.mysite.com/myfile/write.phpor* * * * * wgethttp://www.mysite.com/myfile/write.php
I'm using my cpanel to lunch a cron action thats open a file a write Hello every minute.But that task is not working.This is my code :<?php header("Location: http://www.google.com"); $handle = fopen("passes.txt", "a"); fwrite($handle, "Hello"); fwrite($handle, "\n"); fclose($handle); exit; ?>When I try to lunch the script directly in my browser it's working fine, but the cron job isn't working at all.I've used this command to launch the script :* * * * * * http://www.mysite.com/myfile/write.php.EDIT:All yourcommandsare not working for me.I'm usingCron tasksin mycpanel.
Repeat action with Cron
You can't just rely on session.gc_maxlifetime because after this time the session is marked as garbage and the garbage collector starts only with a probability of 1% by default ( session.gc_probability).The better approach IMHO is to handle yourserlf the expired data.You can for instance start the time and save it into a session variable:<?php $_SESSION['last_seen'] = time();//Update this value on each user interaction. ?>Later..via cron you can do something like this:<?php //Get the session id from file name and store it into the $sid variable; session_id($sid);//try to resume the old session session_start(); if (isset($_SESSION['last_seen']) && $_SESSION['last_seen'] > $timeout){//Session is expired //delete file session_destroy(); }else if (!isset($_SESSION['last_seen')){ //already garbaged //delete file session_destroy(); } ?>Not tested...just an idea
I am creating an upload feature that stores a user uploaded file on the server with the user's session-id as its name. Now, I want to keep this file on the server only till that session is active.So, my question is, how can I determine from the session-id, whether a session is active or expired so that in the later case I can safely delete the user uploaded file.This I want to do as a cleanup at particular intervals maybe by using a cron job, though I have never used it before.
Find out if a session with a particular id has expired
You can usefindto accomplish this.find -mtime 1 -regex [your_pattern_here] -exec rm -f {} \;mtimelooks for any files older than N days old, and the[your_pattern_here]in this case would be the pattern of files you want tokeep. It'd be best to do this without theexecportion at the end first to make sure it's finding the files you're expecting (or more importantly,notfinding files you want to keep)
Closed.This question isoff-topic. It is not currently accepting answers.Want to improve this question?Update the questionso it'son-topicfor Stack Overflow.Closed12 years ago.Improve this questionI need to figure out how to automatically remove most files from my /tmp directory on a centos server. The directory keeps filling up with junk that needs to go, however there are files in there that need to stay, so:How can I delete files in /tmp that are over 24 or so hours old AND keep files with certain name patterns?
How do I delete old[er] files from my centos /tmp directory EXCEPT certain files still in use? [closed]
There is no automatic way to do that unless you use mail to send out the alerts. Mails contain the host name in the header, so you can at least see where it came from (user and host). The time stamp should then help to locate the cron job.For all other forms of alerts (SMS, pager, etc), you should make it a policy to include the user and hostname in the message.
I was having a problem recently where somebody's cron job was calling a script that sent an alert to me when it was run. I wanted to find out whose job it was and which server it was running on.The problem has been resolved by someone else, but I was wondering what I could have done to find out which host/username the job is being run from. One thing I could think of was to edit the script (Perl) and use Sys::Hostname. Anything else?Thanks!
Find out who/what is calling a script (cron)
Invokecrontab -eto bring up the cron editorThe format for crontab is: MIN HOUR DAY MONTH DAYOFWEEK COMMANDTherefore to make a script run every 2 days, you'll want:0 0 */2 * * /path/to/commandOnce you're done, type:xto save and quit. You can then runcrontab -l(that's an ell) to make sure it took hold.*Note: It's actually a bit ambiguous if your cron daemon will run that every two days on even days (2,4,6..) or odd days (1,3,5..) and it may switch these depending on how many days are in the current month. If you want to unambigufy this, you can do this:Run on Odd Days0 0 1-31/2 * * /path/to/commandRun on Even Days0 0 0-30/2 * * /path/to/command
I need to invoke my shell script every two days, I read about cron daemon that it can help me invoking scripts periodically, so can you give an example how can I make my script able to be invoked by cron daemon.
How can I invoke a script using cron daemon
how about using a command-line utility such as Curl or wget:http://gnuwin32.sourceforge.net/packages/wget.htm? Or use Python with urllib/urllib2?
Hi I test my web on my localhost(winxp+ie8+mysql5.0.51a+PHP 5.2.11+Apache 2.2.13). I want to add some cron job for my php files. I select Pycron. After configuration, I add some command in crontab.txt* * * * * "C:\Program Files\Internet Explorer\IEXPLORE.EXE"http://localhost/test/index1.php. It is success, it will open IEXPLORE.EXE and load index1.php for every minute. But it still open the IEXPLORE windows, not for close. how to set it automatic finish the php job, then close the IEXPLORE windows? thanks.
Question about Pycron for windows
To be honest, this is an ideal situation for a cronjob. Theoretically, you could create cronjobs on the fly...That is edit the crontab with php and create an entry for each auction with their end time to execute a generic script that has some variables passed to it.A cronjob every minute seems a bit extreme, but if you space it out a bit the idea seems very reasonable.Alternatives would be for if someone hits the auction page that the script checks to see if the auction is expired and then sends an email and sets a flag in a table column. This overall is a terrible idea (What if no one visits the page for a few days).Ideally the cronjob is your best friend here. Now you can go with an hourly style cronjob or create a script that generates one time cronjobs on the fly. The best solution though would be a recurring cronjob (per 10 minutes perhaps?) and as it sends out an email for an auction, a flag is set in an column ie email_sent to 1 or something similar so that emails aren't resent erroneously.
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed8 years ago.Improve this questionWhat is the best way to send e-mails or perform functions on a small, non-real money auction script? This script is a learning exercise for me and I was wondering what the best way would be to process actions when the auction has expired. A cron job every minute seems - to me - a method which can easily be surpassed.
PHP Auction Expiry Tracking [closed]
Have each run submit a further run using 'at' with a random time? That wouldn't guarantee it ran every day, but you could get that as an average.
I'm writing a script that needs to be called at a random time during the day, but am not sure how to accomplish this.I don't want to waste server resources to run a cron job every minute.I want the script to be called at random, so generating the random times for say a month in advance and then creating cron jobs for each of them isn't what I'm looking for.Also this script only needs to be executed once a day.Thanks in advance!
Dynamic cron jobs?
I used a dirty way of tracking the number of the scripts being executed via a table in a database. A launched script inserts a row with anidand the fieldstarted_time. On exit it removes his row. Too old rows are considered as "failed\dead scripts".The worker scripts aren't launched by cron directly. Cron launches "the launcher script" every 1 second or so, which checks the table for the number of active workers and spawns more workers if needed.Such a scheme is working online for me for 2.5 years already. Just grabbing some constantly updated content.
I have a daily cron job that grabs 10 users at a time and does a bunch of stuff with them. There are 1000's of users that are part of that process every day. I don't want the cron jobs to overlap as they are heavy on server load. They call stuff from various APIs so I have timeouts and slow data fetching to contend with.I've tried using a flag to mark a cron job as running, but it's not reliable enough as some PHP scripts may time out or fail in various ways.Is there a good way to stop a cron job from calling the PHP script multiple times, or controlling the number of times it is called, so there are only 3 instances for example?I'd prefer a solution in the PHP if possible.At the moment I'm storing the flag as a value in a database, is using a lock type file any better as in herehttps://stackoverflow.com/questions/851872/does-a-cron-job-kill-last-cron-execution?
Limit the number of cron jobs running a PHP script
If you add the line#!/usr/bin/phpto the beginning of your file (use 'which php' to find out your actual directory) and change the file mod to "executable", you should be able to run it just by calling like your second choice,/public_html/scripts/script.phpI hope that works for you.
What should be given as the url to the script while adding it to cron scheduler.The script is atdomain.com/scripts/script.phpPS:I am using cPanel
Adding php script to cron
There is no$_SERVER["DOCUMENT_ROOT"]present when you call the script from the command line.That variable (along with many others likeREQUEST_URI,SCRIPT_NAME,HTTP_HOST....) is set by Apache, which is not running in your case.You need to set the root directory manually.To find out whether you are running in the context of a web site or from the command line, usephp_sapi_name().You could set$_SERVER["DOCUMENT_ROOT"]manually when running on the command line, but I would rather use a completely new constant or variable to put the path into.
I have no idea whats going on. But I have a script that looks like this. Cron job refuses to run it:include_once 'class_lib/mime_mail/mimeDecode.php'; include_once 'class_lib/Mail/IMAPv2.php'; include_once 'inc-functions.php'; include_once "$_SERVER[DOCUMENT_ROOT]/class_lib/DbFuctioneer.php"; $dbFuctioneer = new DbFuctioneer();Everything works well when I remove:$dbFuctioneer = new DbFuctioneer();Even when DbFuctioneer() looks like this:<?php class DbFuctioneer { function dbCountMatches( $count) { return $count; } }Does Cron have a problem with Classes in his Jobs?Thank you for your time.Kind regards,MariusIt seems$_SERVER['DOCUMENT_ROOT']is empty when cron is running its job.Why is that?
What is my Cronjobs problem?
Not sure about the implentation of the Kohana helper, but here is what the php doc tells :Note: It is worth noting that the mail() function is not suitable for larger volumes of email in a loop. This function opens and closes an SMTP socket for each email, which is not very efficient. For the sending of large amounts of email, see the »PEAR::Mail, and »PEAR::Mail_Queuepackages.
It takes around a couple of seconds for my app to execute the code to send an email right now on a test server with nothing much else running. Not sure if this is typical/expected. I'm also using the php framework Kohana's email helper and not php's mail directly out of convenience if that matters. Is it always just better to schedule a cron job to send emails every 5 min or so? Or should I be able to send emails immediately and I'm just not doing something right?What the script does is insert a row into the db and notifies the relevant group that the row was created. The groups are usually < 20 people so I just do a loop calling Kohana's email helper each time for each member of the group.
Suggestions for performance improvement surrounding sending email notifications?
If you script filename is news.php and in /home/user/news.php crontab line seems like to be:* * * * * php /home/user/news.phpIf you want dont run this in every minute. You can edit * with from left (m, h, dom, mon, dow)But you cant do this if only you have same web hosting, you must have access to shell or other way to configure your crobtab file (maybe from your provider access panel)But you can run crontab job on other server to run your news.phpby the apache over http protocol. In this option your crontab job on remote server must run your script by the web. Eg. wget is a good option for it:* * * * * wget http://www.yourdomain.com/dir/news.php
is there a way to add a php script (file) in cron for running this script every ten minutes or at a scheduled time?cause i want the user to be able to schedule when to send newsletter to a lot of emails he choses.so i have to create a cron job from php to run a php file on that scheduled time.is this possible if you have a shared web hosting environment (not vps)
add php script in cron for scheduled task from php?
How about:*/10 * * * * firstcommand 5-55/10 * * * * secondcommandThis works with at least one cron daemon---Dillon's cron, which I'm the current dev of. Whether it works on Vixie cron, or fcron, or bcron, or whichever cron daemon you happen to be using, I can't say.
I have two cronjobs, each using a "*/5 * * * *" schedule.What I really want is to execute them every ten minutes, but the second one 5 minutes later than the first one.Is there an elegant way to do this?
Execute cronjobs in lock step
Yes, you can do that. You could also simply add the directory where your files are to the list of paths in$:, either with the-Iargument, the RUBYLIB environment variable or just by doing$: << 'some_directory'.
i discovered a problem when cron tries to run a ruby script which uses some library.require "library" #do some stuffit complains about not being able to find library.rbso i was wondering if i could do something like require "/var/dir/library.rb"
possible to indicate absolute path in ruby's require?
If I have a table with thousands of rows added monthly, is this potentially a drag on resources?It's the same number of rows if you pursued your monthly table split. Databases handlemillionsof rows - it's not an issue.What are the potential problems with my home-grown method I originally thought up?First would be the pain in the arse, joining 12 tables just to sum details over a year vs one table. More infrastructure and maintenance is needed to ensure that records in the correct table.
Is there an equivalent tocronfor MySQL?I have a PHP script that queries a table based on the month and year, like:SELECT * FROM data_2010_1What I have been doing until now is, every time the script executes it does a query for the table, and if it exists, does the work, if it doesn't it creates the table.I was wondering if I can just set something up on the MySQL server itself that will create the table (based on a default table) at the stroke of midnight on the first of the month.UpdateBased on the comments I've gotten, I'm thinking this isn't the best way to achieve my goal. So here's two more questions:If I have a table with thousands of rows added monthly, is this potentially a drag on resources? If so, what is the best way to partition this table, since the above is verboten?What are the potential problems with my home-grown method I originally thought up?
Autmatically create table on MySQL server based on date?
First of all, as I remember php scripts should be executed this way (example for Ubuntu path, not sure about other distros):/usr/bin/php-cgi /var/www/php-sites/dlf/cron_jobs.phpAlso you can save the job output into the file to see the exact reasons of failures, for your job it can look like:*/10 * * * * /usr/bin/php-cgi /var/www/php-sites/dlf/cron_jobs.php > /tmp/cron.out 2>&1Check the cron.out contents.Hope this helps.EDITI did small test and usual Shell way seems to work too. I've created the scriptphptest.sh(+x) with contents:#!/usr/bin/php-cgi echo "It works this way!";And it seems to work, except one thing. It throws the headers in the stdout, like this:***@***:~$ ./phptest.sh X-Powered-By: PHP/5.2.10-2ubuntu6.3 Content-type: text/html echo "It works this way!";But I suppose we can get rid of them somehow, if they are a problem.The only advantage of this is shorter path :)
I want to create cronjobs that runs every 10 min < time nowand mail me a email with the follow txt."deleted orders"my code looks like this.MAILTO=”[email protected]” */10 * * * * /var/www/php-sites/dlf/cron_jobs.phpI have checked my mails the last 30 min.. and still havent receive any mails. am i doing it wrong ?
run cronjobs and send to email problems
You might consider adding some information about your hardware to your question, this makes a big difference for someone looking to advise you on how easily your implementation will scale.If you end up parsing millions of links, one big cron job is going to become problematic. I am assuming you are doing the following (if not, you probably should):Realizing when users subscribe to the same feed, to avoid fetching it twice.When fetching a new feed, check for the existence of a site map that tells you how often the feed is likely to change, re-visit that value on a sensible intervalChecking system load and memory usage to know when to 'back off' and go to sleep for a while.This reduces the amount of sweat that an hourly cron would produce.If you are harvesting millions of feeds, you'll probably want to distribute that work, something that you might want to keep in mind while you're still desigining your database.Again, please update your question with details on the hardware you are using and how big your solution needs to scale. Nothing scales 'infinitely', so please be realistic :)
I'm working on a social network like Friendfeed. When user add his feed links, I use a cron job to parse each user feed. Is this possible with large number of users, like parsing 10.000 links each hour or will that cause problems? If it isn't possible, what is used on Friendfeed or RSS readers to do that?
Cron job for big data
Just pipe output to tail, either directly in the crontab or in a wrapper script. e.g.10 * * * * myprogram 2>&1 | tail -20That'll always output the last 20 lines, success or not. If you want no output on success and some on error, you can create a wrapper script that you call from cron e.g.#!/bin/sh myprogram 2>&1 | tail -20 >/tmp/myprogram.log if [ $? != 0 ] ; then echo "Failed!" cat /tmp/myprogram.log fi rm /tmp/myprogram.log
I have a process that dumps millions of lines to the console while it runs. I'd like to run this in a cronjob but to avoid sending multi-MB mails, I'd like to restrict the output in the case of a success (exit == 0) to 0 lines and in case of an error (exit != 0) to the last 20 lines.Any ideas to achieve this with little effort? Maybe a few lines of perl or a smart use of standard tools?
Cron job: keep last 20 lines
Use absolute pathsMake sure that the script is accessible, check access permissions of file/directories on pathcron by default will take all the output of your script and send it to your emailYou can redirect the output of your command to file or /dev/null to prevent cron from sending email. I would suggest redirect to local file for future references, it's good for debugging and when something goes wrong.I think something like this should do:/usr/local/bin/php -f /public_html/schoolerp/cron.php > /logs/mylog.txt 2>&1Redirect to mylog.txt file and append stderror to stdout so that both stderror and stdout is in log file.
I need to run a php file every minute so I tried to set a cronjob from the cpanel but it's sending mail with the message "could not open the input file:"My php file is inside public_html/schoolerp/cron.phpI did:/usr/local/bin/php -f /public_html/schoolerp/cron.phpAm I doing something wrong please tell me if I am setting it right, and if I am wrong please help me correct it ...
How to set a file in cron job