Response
stringlengths 8
2k
| Instruction
stringlengths 18
2k
| Prompt
stringlengths 14
160
|
---|---|---|
Should I be using a cron job - if so, how can I check that sessions are finished?Yes. You do this based on the file last modification time (in your case the file is a directory). If it's older than the maximum session age, delete the directory.You can use thefindWikipediacommand for that.You find an example script in your PHP folder, see as wellDeleting old session files from custom set session folder?andcleanup php session files.
|
I am looking at how I can run a script or function when a user's session ends so that I can delete temporary files which may be required.I have searched around SO to find a solution to this problem and came acrossthisbut I find I am a little out of my depth and I find the PHP documentation regarding GC to be confusing (and from what I understand from the documentation - it is not really what I need).I looked at the page onsession_set_save_handlerand came up with this:session_set_save_handler( '', '', '', '', 'deleteDocs');
function deleteDocs()
{
rmdir('user/' . rawurlencode($_SESSION['data']['user']['details']['email']) . '/temp');
}However, this function does not run at all. Frankly, with this, I feel like I do not know what I am really doing.I tried using GC and looked atsession.gc_divisorandsession.gc_probabilitybut I cannot edit php.ini anyway.Can this be achieved. Should I be using a cron job - if so, how can I check that sessions are finished?
|
Run script when session ends
|
Little checklist:Is your cron running -> u2ix [checked]Permissions to use cron [checked]Does your script run in the shell [checked i hope]Run a litte script that shows you the environmet in your cron (-> env) / it isneverthe same as in your shell :-)after execute your php-creat-cronjob-script check with corntab -l the crontab--
do you get mail from your cron ?
|
I am trying to setup a CRON job using PHP, but am not having any luck so far.I am following this tutorial:PHP - Create a Cron Job with PHP(dead link)I have created the script file with the correct permissions, but the script is not being processed.Any ideas?
|
How can I debug a PHP CRON script that does not appear to be running?
|
kubectl create job manual-job --from=cronjob/some-cronjobYou can use above method only to launch a job execution of a declared cronjob and whats more important(unfortunately for you) - you are able to thatonly using kubectl cli.During research I also found myansweron a similar questionKubernetes Run job using CronJob. There is also try in that example to achieve very similar thing as you trying to rich(but vise-versa. In the provided example there is a try to create cronjob bases on already existed job)..jobTemplate:
spec:
labelSelector:
name: pi # refer to the job created aboveBoth of your questions make sense, it would be very useful to have such an option, but, as I said in the beginning - that's currently not possible.For test purposed - use provided command.For regular usage - currently have no idea how to help you. Hope future releases will add this feature
|
I need to execute a job create from cronjob in kubernetes.
Manualy I can run it like this:kubectl create job manual-job --from=cronjob/some-cronjobThough I'm not sure how to translate this to yaml.ProbablyI need to put afrom:section in the spec ,but I'm not sure how.
|
Create job from cronjob in kubernetes .yaml file
|
I've found the solution! The issue was caused by my firewall settings...They were blocking the loopback which wp-cron requires to function properly.Installing this plugin:https://wordpress.org/plugins/wp-crontrol/showed me
the error message "cURL error 28".From there, I was able to figure it out.
|
I am trying to hook into thewoocommerce_order_status_changedaction and add a single event to the wp cron to execute immediately (so that the request-response cycle is not blocked):add_action('woocommerce_order_status_changed', 'on_new_status', 10, 3);
add_action('send_new_status_custom_hook', 'logic_on_new_status', 10, 2);
function on_new_status($order_id, $from, $to){
wp_schedule_single_event(time(), 'send_new_status_custom_hook', array($from, $to));
}
function logic_on_new_status($first, $second){
// code
}The eventisadded to the cron (I can see it using a plugin), but not executed. When I click on "execute" manually, itisexecuted.What could the problem be?I am using Wordpress 5.3.2.Thanks!
|
Wordpress cron – event added to queue but not firing
|
Seeing as though its a cronjob, that starts standard Kubernetes Jobs, you could query for the job and then check it's start time, and compare that to the current time.Note: I'm not familiar with stackdriver, so this may not be what you want, but...E.g. with bash:START_TIME=$(kubectl -n=your-namespace get job your-job-name -o json | jq '.status.startTime')
echo $START_TIMEYou can also get the current status of the job as a JSON blob like this:kubectl -n=your-namespace get job your-job-name -o json | jq '.status'This would give a result like:{
"completionTime": "2019-09-06T17:13:51Z",
"conditions": [
{
"lastProbeTime": "2019-09-06T17:13:51Z",
"lastTransitionTime": "2019-09-06T17:13:51Z",
"status": "True",
"type": "Complete"
}
],
"startTime": "2019-09-06T17:13:49Z",
"succeeded": 1
}You can use a tool like jq in your checking script to look at thesucceededortypefields to see if the job was successful or not.So with your START_TIME value you could get the current time or the job completion time (completionTime) and if the result is less than your minimum job time threshold you can then trigger your alert - e.g. POST to a slack webhook to send a notification or whatever other alert system you use.
|
I'm trying to monitor a CronJob running on GKE and I cannot see an easy way of checking if the CronJob is actually running. I want to trigger an alert if the CronJob is not running for more than a X amount of time and Stackdriver does not seem to support that.At the moment I tried using alerts based on logging metrics but that only serves me to alert in case of an app crash or specific errors not for the platform errors themselves.I investigated a solution using Prometheus alerts, can that be integrated into Stackdriver?UPDATE:
Just a follow up, ended up developing a simple solution using log based alerts on Stackdriver. If the log doesn't appear after X time then it will trigger an alert. It's not perfect but its ok for the use case i had.
|
Monitor Cronjob running on GKE
|
In production, you should run Celery, Beat, your APP server etc. as daemons [1] using Supervisor/Upstart/Systemd/.../.... There is a section about this in the Celery documentation. [2]My favorite tool is Supervisord [3]. Here is Supervisord example configuration for Celery:https://github.com/celery/celery/tree/master/extra/supervisordand herehttps://github.com/illagrenan/ubuntu-supervisor-configurationis a tutorial about installing Supervisord on Ubuntu.(...) Supervisord starts processes as its subprocesses, and can be
configured to automatically restart them on a crash. (...)Source:http://supervisord.org/introduction.html#introduction[1]https://en.wikipedia.org/wiki/Daemon_(computing)[2]http://docs.celeryproject.org/en/latest/userguide/daemonizing.html[3]http://supervisord.org/
|
I useCeleryandCelerybeatin my django powered website. the server OS is Ubuntu 16.04. by using celerybeat, a job is done by a celery worker every 10 minutes. sometimes the worker shuts down without any useful log messages or errors.
So, I want to find a way in order to detect status (On/Off) of celery worker (not Beat), and if it's stopped, restart it automatically.
how can I do that?
thanks
|
how to detect failure and auto restart celery worker
|
cron update in multiple servers is possible,Here'sa link! please refer this link
|
Versions:Ruby 2.3.1
Rails 4.2.4
Whenever 0.9.7Our configuration:I am able to deploy my application on NFS successfully. Both EC2 instances are mounted on NFS, so both server points to same code. All working fine.The problem is, as i am deploying on NFS, capistrano-whenvever writes/updates cron on NFS, where no crone is executed as its simple file server.I would like to write cron jobs on EC2 instance1 or EC2 instance2.I have gone throughwhenever gem have cronjob on only one machine?, but didn't succeed.Any help would be appreciated.
|
Whenever gem: cron update in multiple server environment
|
Needs to changeWithDailyTimeIntervalScheduletoWithSimpleSchedule. Warning: there are probably better ways to deal withstartDate.DateTime startDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, 0 ,0, DateTimeKind.Utc);
ITrigger trigger = TriggerBuilder.Create()
.StartAt(new DateTimeOffset(startDate, new TimeSpan(0)))
.WithSimpleSchedule
(s =>
s.WithIntervalInMinutes(30)
.RepeatForever()
)
.Build();Test:var times = TriggerUtils.ComputeFireTimes(trigger as IOperableTrigger, null, 10);
foreach (var time in times)
Console.WriteLine(time.UtcDateTime);
Console.ReadKey();Result:14.12.2015 15:00:00
14.12.2015 15:30:00
14.12.2015 16:00:00
14.12.2015 16:30:00
14.12.2015 17:00:00
14.12.2015 17:30:00
14.12.2015 18:00:00
14.12.2015 18:30:00
14.12.2015 19:00:00
14.12.2015 19:30:00
|
I have a job, which triggers in every 30 minutes. I've set a test table and record information, when job fires. For example :2015-12-13 19:30:00.043
2015-12-14 12:30:00.043
2015-12-14 13:00:00.043
2015-12-14 16:00:00.043But as you can see it does not trigger in every 30 minutes. 19:30 then 12:30.. I've noticed that if i open managament studio and check this table, next job would trigger 100%. Why is that happening, is it quartz.net bug?
P.S i am using asp.net mvc and this is code :ITrigger trigger = TriggerBuilder.Create()
.WithDailyTimeIntervalSchedule
(s =>
s.WithIntervalInMinutes(30)
.OnEveryDay()
.StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(0, 0))
)
.Build();
scheduler.ScheduleJob(job, trigger);
|
asp.net cron job quartz.net bug, not firing always
|
+50I think you are being limited by the number of cron jobs you can run in a day, IIRC hostgator has a daily limit for basic plan. To work around this limitation, IMO, you have two choices:Go tosleepfor 60 secondsBasically, run the cron job at the required hour every day, and check for your condition, if it is notTrue, then go to sleep for 60 seconds.if($row["fake_time"] == date("Y-m-d H i")){
//do stuff
} else {
sleep(60);
}This way, you have a single cron job, though it runs for a long while. In case you can run the cron job only daily, and you want to run at random hour as well as minute, you can change your logic and go to sleep for3600seconds for hourly sleeps, and then go for minutely sleeps of 60 seconds.You might need to setupset_time_limitaccordingly.Set up easycronIn case your cron jobs are terminated abruptly because the time limit can't be set, you will need to hit usingeasycronservice.In this case, put the above script code in a php file, sayscript.php, and schedule a cronjob to hit with a get request on this script. Your command in this case will look something likewget your.domain.com/script.php
|
I have been trying to do random cron jobs where I choose the year month date and hour but the minute is randomised.My first attempt was to run the cron every min and then compare a random date with todays date:I inserted a random date into a database columnfake_timein the format2014-10-26 17 rand(0,59). In the php page where I run the cron every min:if($row["fake_time"] == date("Y-m-d H i")){
//do stuff
}And this worked perfectly. But then I found out that I can't run the cron every min because my hostor (hostgator) wont allow me to! Have you got any ideas on how I can do this any other way?Or should i just set it up onhttps://www.easycron.com/instead?
|
Create random minute cron job for a specific date and hour
|
Break the problem in half. First try sending only email from the cron job to see if you are getting it to even run. Put this above in a file and have your cron job point to it:#!/bin/bash
/bin/mail -s "test subject" "yourname@yourdomain" < /dev/nullThe good thing about using this tester is that it is very simple and more likely to give you some results. It does not depend on your current working directory, which can sometimes be not what you expect it to be.
|
I'm trying to create a cron that daily backups my MySQL slave. The backup.sh content:#!/bin/bash
#
# Backup mysql from slave
#
#
sudo mysql -u root -p'xxxxx' -e 'STOP SLAVE SQL_THREAD;'
sudo mysqldump -u root -p'xxxxx' ng_player | gzip > database_`date +\%Y-\%m-\%d`.sql.gz
sudo mysqladmin -u root -p'xxxxx' start-slaveI made it executable bysudo chmod +x /home/dev/backup.shand entered in tocrontabby:sudo crontab -e
0 12 * * * /home/dev/backup.shbut it doesn't work, if I only run in the command line it works but not incrontab.FIXED:
I used the script from this link:mysqldump doesn't work in crontab
|
MySQL dump CronJob
|
You can (assuming you have permission) directly modify your crontab file using Java's many file I/O functions. The file can (at least on my system) be found at:/var/spool/cron/crontabs/paxdiablo(for the userpaxdiablo). Simply make whatever changes you want to this file and then send a HUP signal to thecrondaemon.However, directly editing that file is frowned upon and indeed it may well be protected from you.To do itproperly,you can use thecrontab -lcommand to capture the current contents to a file (eg,me.cron). Thecrontab -lcommand writes your crontab file to standard output, unlikecrontab -ewhich tries to bring it up in an editor.Then you can use whatever means you wnt to modifythatfile (it's yours because you created it).Then, runningcrontab me.cronwill install that file (with any changes you've made) and notifycronso that it re-reads it.
|
I want to be able to setup linux cron jobs from a java program.I know to setup a cron job, i use the crontab tool:crontab -eand then specify the cron expressions.How do i do this programmatically from a java program?Thanks
|
setting up linux cron jobs from java
|
There isDate getFireTimeAfter(Date afterTime)In the trigger interface.You could check what the next firetime t-1 is when t is the time you want to Check. If the result equals t you know the answer.
|
I am using thequartz schedulerto schedule some jobs in Java using cron expressions, and have come across the need to find you whether agiven timestampis within a specified cron expression. That is to say, would a scheduled job with this cron run at the given timestamp?I am not confined to using quartz library to solve this problem, so any solution is welcome.
|
How to find if a given timestamp is within a cron-expression?
|
In 2013 - when this question was created - there were not as many workflow/scheduler management tools freely available on the market as they are today.So, writing this answer in 2021, I would suggest using Crontab as long as you have only few scripts on very few machines.With a growing collection of scripts, the need for better monitoring/logging or pipelining you should consider using a dedicated tool for that ( likeAirflow,N8N,Luigi... )
|
I tried to run my python scripts using crontab. As the amount of my python scripts accumulates, it is hard to manage in crontab.Then I tries two python schedule task libraries namedAdvanced Python Schedulerandschedule.The two libraries are quite the same in use, for example:import schedule
import time
def job():
print("I'm working...")
schedule.every(10).minutes.do(job)
schedule.every().hour.do(job)
schedule.every().day.at("10:30").do(job)
while True:
schedule.run_pending()
time.sleep(1)The library uses thetimemodule to wait until the exact moment to execute the task.But the script has to run all the time and consumes tens of Megabytes memory. So I want to ask it is a better way to handle schedule jobs using the library? Thanks.
|
Crontab vs Schedule jobs in python?
|
You could use something like this:ssh -tt otherhost "your_monitoring_script 2>&1" 2> /dev/nullThat way the errors from ssh go in the bucket, but the errors from your script are shown in stdout. For that to work you should mark errors from your script as "ERROR:" so that you can find them back if your script provides lots of output.
|
I'm defining something like this in mycrontab:* * * * * ssh -tt otherhost whoamiAnd I'm getting the following output:tcgetattr: Invalid argument
meRunningsshwith fewer-ttoptions leads to other errors besidestcgetattr.The solution posted inwhy is the `tcgetattr` error seen when ssh is used for dumping the backup file on another server?doesn't really work well because in this case I'm using severalsshconnections to run monitoring scripts on different hosts and I need to capture output sent tostderrand email it.Any ideas on how to workaround this?
|
ssh from crontab returning 'tcgetattr: Invalid argument'
|
You may first readSecuring URLs for Cronand then implement some (or all) of the proposed methods, I think that by requiring "admin" permissions for Cron tasks and by checkingX-Appengine-Cron: trueyou are getting quite safe even without using SSL.You don't have to change your Base Handler, just create another handler just for Cron jobs.
|
I have an App Engine app that requires SSL for access to any URL.Tasks execute without any issues and required https (SSL).The cron job I am trying to run also requires SSL (it's checked at the Base Handler level) but it fails to run. I am fairly certain that is the issue because the URL runs fine from a browser using GET but it does require https. I don't really want to have to change the Base Handler (in python) to allow some requests to go through without SSL.There is no log entry in App Engine logs at the time the job ran (which ran according to schedule).The status of the job is "failed".Is there a configuration parameter for App Engine cron jobs to use SSL or is this a feature request of the App Engine team?
|
Can App Engine cron jobs use https (SSL)?
|
First of all, I'm assuming you are using CI ver 2> (CLI support was not available before).Secondly, lets say that the page you are trying to fire under cron ishttp://www.mysite.com/index.php/cronjobs/thejobThe correct command would be:/usr/bin/php /var/www/rootCIfolder/index.php cronjobs thejobReplace/usr/bin/phpwith the location of your php executable and/var/www/rootCIfolderwith the location of your CI folder.You need to have php compiled with command line support. You can verify this by:# php -v
PHP 5.3.3 (cli) (built: Jul 3 2012 16:53:21)
|
I'm trying to set up aCRONjob to make some database changes on aCodeIgniterinstall and having issues with the host that are stopping it from working. The host's CRON setup only allows you to execute a PHP file rather than calling a URL.What I've tried:Curl, wget, file_get_contents, fopen, http_getfrom a static PHP file - all not allowed by the host/path/to/php /path/to/index.phpcontroller method - to use the command line interfaceAfter unfruitful conversations with the host I'm out of ideas. Does anyone know how I could call a controller method from a static PHP file without the above?
|
CodeIgniter CRON job
|
When you create a new job thecrondaemon call the functionjob_add(job.c), this function alloc the memory to the job and add it to the tail of the job list.
The job is allocated on the heap, so theorically you're limited just by the RAM installed on your machine.Some notes from the CRON code:The job structure:typedef struct _job {
struct _job *next;
entry *e;
user *u;
} job;Each user crontab entry is defined by:typedef struct _entry {
struct _entry *next;
uid_t uid;
gid_t gid;
char **envp;
char *cmd;
bitstr_t bit_decl(minute, MINUTE_COUNT);
bitstr_t bit_decl(hour, HOUR_COUNT);
bitstr_t bit_decl(dom, DOM_COUNT);
bitstr_t bit_decl(month, MONTH_COUNT);
bitstr_t bit_decl(dow, DOW_COUNT);
int flags;
#define DOM_STAR 0x01
#define DOW_STAR 0x02
#define WHEN_REBOOT 0x04
} entry;And the user struct:typedef struct _user {
struct _user *next, *prev; /* links */
char *name;
time_t mtime; /* last modtime of crontab */
entry *crontab; /* this person's crontab */
} user;You can see that this structs does not cosume a lot of memory.
If you're curious about how the implementation ofcronwork, you can see the code here :cron ubuntu source.
|
Alright,
I'm thinking of creating a webscript that depends on cronjob..I'm wondering, would it ever make any server damages for the amount of crontabs ?lets say i have 50 crontabs to be done everyday, would it ever hurt the server ?
if no, what's the max amount of crontabs to be added in a linux server @ 512MB memory
|
What is cron job's server usage?
|
What you're doing is called "log rotation", and yes, it is safe to do it by renaming the log file.In Linux, you can rename a file while another application is writing to it, and that application will continue writing to the renamed file. Seethis SO answerfor details.In Windows, you can only rename an open file if the application that opened it set the FILE_SHARE_DELETE flag when callingCreateFile. If the the flag is set, it works the same way it does on Linux (the application continues writing to the renamed file). If it's not set, any attempt to rename the file will fail.You may also be interested in thelogrotatecommand.
|
I have a php script which is generating a log file.
On the other hand I have another script that should be running hourly to process the logfile.In my second script, I want to copy and truncate the log file while it's been writing to without any dataloss.In a limited test I've been using rename, to create the copy and I getting the expected resultsBut I have concerns over the correctness of this approach.Is this safe to do?
|
How to copy a file and truncate original without dataloss using php
|
MapReduce, if outputting to a collection will take multiple write locks out as it writes (as any operation which is creating/updating a collection would). If you are doing an in-line MR, then you avoid that locking (but have limitations on result sizes). Even so, there are still read-locks and the Javascript lock (single threaded for server side JS on mongoDB right now).This is all explained (and will be updated if it changes) here:http://www.mongodb.org/display/DOCS/How+does+concurrency+work#Howdoesconcurrencywork-MapReduceNote: the SpiderMonkey to V8 JS engine migration issues are ones to watch if multi-threading is something you are concerned about.
|
Does MongoDB map reduce lock a collection when performing an operation on it?I have some collections that are widely and intensively used by an application. A Map/Reduce runs in the background every 10 minutes via a cron job, on that widely and intensively used collection.I want to know if there is a high probability that Map/Reduce won't perform well because other operations are in progress (inserts, updates, and mostly reads) on that collection. In particular, I want know if Map/Reduce interferes with normal operations performed on the collection by users.
|
MongoDB - How does locking work for Map Reduce?
|
Inject the Scheduler into one of your beans and invokescheduleJob(). You can pass it anything you want.
|
Currently I'm running Quartz scheduler example in this linkhttp://www.mkyong.com/spring/spring-quartz-scheduler-example/My question is this
How can I add a dynamic time in CronTrigger bean, instead of hard-coded time in here :<property name="cronExpression" value="0/5 * * * * ?"/>I need to read this value dynamically as a parameter passed to my controller.
|
Dynamically scheduling quartz cron job in spring?
|
How about using thecrontabcommand? You could create a file in /tmp called newcronjobs.txt with the cron entries you want to add. And the callcrontab /tmp/newcronjobs.txtThis should add all of the new jobs. I would assume this is pretty secure but just a thought.
|
I need to be able to update the scheduled run times for various jobs from a web page and I am looking for a secure way to do it on a Red Hat Enterprise Linux system. Obviously editing the crontab file directly is a no-no and we limit PHP access to its application directory anyway. Best I can can come up with is to create the updated file in the application directory (one level below webroot) then sudo exec a script that validates the file and moves it into the cron.d directory. Is this secure or is there a better way to do it?ThanksMark
|
Secure way to update cron from a LAMP web page
|
This is an internal php error.File a bugon the imap module (if you want it fixed fast, include anSSCCE).Also note that this is a memory corruption issue, which is usually caused (long) before it is noticed. Therefore, theimap_searchfunction is probably not the buggy one; theimap_*function you used just before it is a good candidate.
|
I have developed a script that uses php'simap_searchand when it gets to the stage of finding the emails with the functionimap_search()i get a error being producedphp in free(): error: chunk is already
freeAbort trap: 6 (core dumped)This script requires to be run through a cron, But when it does it does that above error and seems to abort the script, If i run from the browser it has this error inside the error logs but still runs the script in full.Below is the line it is failing on:$this->mailbox_emails = imap_search($this->mailbox_stream,'ALL');
|
php in free(): error: chunk is already free
|
'bus error' probably means that the program that is being invoked is trying to dereference a null pointer or some similarly invalid memory address. It usually comes from using an uninitialised value (dereferencing a null pointer), or from using a value that has been accidentally overwritten (e.g. when the stack is pushed with saved values, but lengths are miscalculated or the wrong data type used to extract the data).IME, there is rarely any implication of a hardware fault. It's usually a bug - so 'gdb' will usually help much more than 'dmesg'; that said, I was involved in some research on UNIX Systems back in 1991 that suggests that some cores and kernel panics are a consequence of power supply glitches (thunder storms in Austin, Texas), but those don't show up in 'dmesg' output despite being "hardware" :)I'm currently getting this message in a SugarCRM installation, sometimes. About 99% of the time the cron.php works as expected. Sometimes I get a 'bus error - core dumped' message. I'm not getting a core dumped in the directory named in the crontab, though. That makes debugging this slightly more complex - I need to make sure that the core dump is being captured! I'm not too worried, as everything appears to be working. So it is a low priority task... I may find and fix it, eventually, but it is more likely that we'll upgrade to a newer version of PHP, MySQL and Sugar - and those changes may make the problem go away.
|
I have set up a cron job for sending emails from my site using php. It was working fine.
Today I got one error message like this "/bin/sh: line 1: 29681 Bus error".
Could you please tell me what is this bus error and its solutions?Thanks In AdvanceRose
|
Bus Error in cron job
|
The number of cron jobs that run depends on the number of application instances running in the server box. Are you have two instances of rails application running in the same server box?
|
I have a rails app with the whenever gem installed to setup cron jobs which invoke various rake tasks. For reasons unbeknownst to me, each rake task gets invoked twice at precisely the same time. So my db backup task backs up the db twice at 4:00am.Inspecting crontab reveals correct syntax for all of the cron jobs, so I don't think this is an issue with the whenever gem not correctly configuring the cron jobs. Also confusing is that in both staging and production environments and can invoke tasks on the command line and they only run once.Any thoughts on what would cause this? I'm at a complete loss troubleshooting wise.
|
Why would my rake tasks running via cron get invoked twice?
|
namespace :deploy do
desc "write the crontab file"
task :write_crontab, :roles => [:db_admin] do
run "cd #{release_path} && sudo -u root whenever --write-crontab #{application}"
end
endOr there is also apparently a -user option in whenever that can help with this.
|
I’ve been trying to get whenever running on an ec2 instance that was created with ec2 on rails.When I deploy with Capistrano it indicates that the crontab was written, but when I log into the server and run crontab -l it does not seem to have been changed.If I go into the release folder and manually run whenever --write-crontab then run crontab -l - it gets updated properly.Any ideas what could be causing this?Capistrano is not indicating any errors so not sure how to debug, have tried a billion permutations and combinations and nothing changes.
|
javan-whenever not writing crontab with Capistrano deploy
|
You can always put specific minute, hour, day, month in the schedule cron expression, for example 12:15am on 25th of December:apiVersion: batch/v1
kind: CronJob
metadata:
name: hello
spec:
schedule: "15 0 25 12 *"
jobTemplate:
spec:
template:
spec:
containers:
- name: hello
image: busybox
imagePullPolicy: IfNotPresent
command:
- /bin/sh
- -c
- date; echo Hello from the Kubernetes cluster
restartPolicy: OnFailureUnfortunately it does not support specifying the year (the single*in the cron expression is for the day of the week) but you have one year to remove the cronjob before the same date & time comes again for the following year.
|
How can I schedule a Kubernetescron jobto run at a specific time and just once?(Or alternatively, a Kubernetes job which is not scheduled to run right away, but delayed for some amount of time – what is in some scheduling systems referred to as "earliest time to run".)The documentation says:Cron jobs can also schedule individual tasks for a specific time [...]But how does that work in terms of job history; is the control plane smart enough to know that the scheduling is for a specific time and won't be recurring?
|
Schedule a Kubernetes cronjob to run just once
|
According to Laravel docs...(using L5.7 as example)Starting The SchedulerWhen using the scheduler, you only need to add the following Cron
entry to your server. If you do not know how to add Cron entries to
your server, consider using a service such as Laravel Forge which can
manage the Cron entries for you:* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1This Cron will call the Laravel command scheduler every minute. When
the schedule:run command is executed, Laravel will evaluate your
scheduled tasks and runs the tasks that are due.But being in the same boat as you, our log file is being created and owned by root. The best solution would be to create the cron entries using www-data.As@catconin the comments said, "you can use commandcrontab -u www-data -eto edit www-data's cron jobs"And adding the crontab entries usingwww-datais how you fix the permission issues.
|
Closed.This question isnot about programming or software development. It is not currently accepting answers.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.Closed11 months ago.Improve this questionI setup my laravel Task Scheduling on my ubuntu server by add this toroot's crontab* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1So when the cron job is running, it'll create a log file that belong to userroot-rw-r--r-- 1 root root 6839 Jan 11 23:00 laravel-2020-01-12.logBut the user that run the laravel project iswww-data, so whenever there's an API call, I got thePermission deniederror causewww-datacan not access the log file that belong toroot.I try to install contab forwww-databut I can't accesswww-datauser:> su www-data
This account is currently not available.What is the best user to install cronjob for Laravel?
|
Laravel - Ubuntu - Crontab: Should I install cron job for user root? [closed]
|
There can be multiple issue with this. The one's I have encountered are:1) If your script is using any PATH variable from system then that has to be added to crontab manually.2) You should add a relative path to your script to run.3) Crontab entry should always have a newline at the end of the file.These are all I thing I have come across as errors while using crontab.Hope this might help you.
|
I am trying to execute a command throughDjango Crontabeveryday. Here is what I am doing:First, I addeddjango_crontabinINSTALLED_APPSFYI, I have written a Django commandsendalertswhich is working perfectly fineNow I am trying to run that command throughcrontabon regular intervalsThis is what I added in mysettings.pyCRONJOBS = [
('* * * * *', 'django.core.management.call_command', ['sendalerts']),
]When I run this command throughpython manage.py crontab addit doesn't give any error. It also list down cronJob when I check with this commandpython manage.py crontab showBut problem is it doesn't execute the code which is written in mysendalertscommand.What can I do to check what is that I am doing wrong or what can be the error which I can fix to make it work?Edit:Output ofcrontab -eis* * * * * /usr/local/bin/python /home/wukla/app/app/manage.py crontab run 455e70156896954803547b6f6d845f9b # django-cronjobs for app
|
Crontab is running but still not executing command Django
|
Quartz does not support the feature. However, this can be achieved incron-utilswith a custom cron definition. In order to mirror the same definition ofQuartz, but without the restriction regarding day-of-month and day-of-week, you could do this:CronDefinition cronDefinition =
CronDefinitionBuilder.defineCron()
.withSeconds().withValidRange(0, 59).and()
.withMinutes().withValidRange(0, 59).and()
.withHours().withValidRange(0, 23).and()
.withDayOfMonth().withValidRange(1, 31).supportsL().supportsW().supportsLW().supportsQuestionMark().and()
.withMonth().withValidRange(1, 12).and()
.withDayOfWeek().withValidRange(1, 7).withMondayDoWValue(2).supportsHash().supportsL().supportsQuestionMark().and()
.withYear().withValidRange(1970, 2099).withStrictRange().optional().and()
.instance();
CronParser parser = new CronParser(cronDefinition);
parser.parse("0 0 0 3 * MON#1");
|
I am usingcron-utilslibrary for scheduling purpose. When I provide both DoM and DoW then I get following exceptionBoth, a day-of-week AND a day-of-month parameter, are not supported.I found out that this exception is consistent with QUARTZ specification.I want to know why it is not supported ? Because it seems to be valid requirement to run something like on "5th of September only if its on Sunday"Do I need to write two separate expression and take its intersection?What is recommenced solution for this issue?
|
QUARTZ : Both, a day-of-week AND a day-of-month parameter, are not supported
|
You should fix by replacing@Componentwith@Serviceand@EnableScheduling.@Service
@EnableScheduling
public class ScheduledTasks {
. . .
}
|
I have an application developed onspring frameworkwithmaven. I have many modules (each one has its ownpom.xmlfile) and I have the genericpom.xmlto compile the entire project.UsingmavenI compile a.warfile and I deploy this one in aJettyserver, but now I have another problem. I need to configure a function that will execute some code every couple of minutes.
I tried to configure it likeat the following link, so having:I edited the specific pom.xml file and I add this:<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>1.2.1.RELEASE</version>
</dependency>On dependencies list, I added this in plugin list:<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>I created in the same module one file that defined this class:@Component
public class ScheduledTasks {
private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
@Scheduled(fixedDelay = 5000)
public void reportCurrentTime() {
log.info("The time is now {}", dateFormat.format(new Date()));
}
}but it doesn't work for me. Logs don't print anything.
I've been struggling with this issue for a while but I didn't manage to find any solution also taking a look at other related Q/A on StackOverflow.What Am I doing wrong? How can I fix this?Thanks in advance.
|
Configure a scheduled task on .war file created by Spring/Maven
|
I have just used site for my application.https://crontab.guru/#30_2,10,18___*you can write something like : 0/45 * * * *
|
Is there any java library/API which can modify cron expression from one timezone to UTC?For example:I need something like this:newCronExpression = convert (oneCronExpression, fromTimezone, "UTC")Let me give you one example:My local timezone is IST i.e.GMT+5.30.Current local time is:11:20 AM.I want a job to run in 45 min of every hour.So, my cron expression:45 * * * *Hence I am expecting my job to run after 25 min ( as starting time is11:45 AM)but my job is running as per UTC.Current time in UTC :05:50 AMAs per cron expression 45 * * * , the starting time will be 06:45 AM at GMT.So, the job will be actually started after 55 min.Expected : After 25 minActual : After 55 minSo,if I am converting my local cron expression 45 * * * to 15 * * * * at
GMT, then actual waiting period will be same as expected.The question is how will I convert my local cron expression to GMT for
all usecase in my java program.If you have better approach, please do let me know.*I can't schedule it as crontab in unix machine. This has to be handled in Java program.Thanks in advance.
|
Converting cron expression from one timezone to UTC in java
|
If you are using PHP-FPM, you can usefastcgi_finish_request:This function flushes all response data to the client and finishes the request. This allows for time consuming tasks to be performed without leaving the connection to the client open.This way you can use PHP's native functions to do your webrequest after the user has already gotten the response. An example on how to use this function can be found inexample of how to use fastcgi_finish_request()If you are not using PHP-FPM, you can use a JobQueue likeGearmanto do work outside the original request. This is probably the most reliable way of doing it, as it's a dedicated system for handling these kinds of jobs.Also note thatcurl can do async http requests. If the issue is that you dont want to wait for the http response, this might be an easier solution than introducing a JobQueue.Last but not least, you can fork additional PHP process to do the work. SeeHow can I do time consuming task after sending response to clientandphp execute a background process
|
I'm currently using the following php exec command to load a url on the server side as I need a solution that doesn't involve a cron job and that is also asynchronous i.e. the user can navigate away form the page once the task is initiated and the task will still execute:exec("nohup curl ".$dbupdateurl." > /dev/null 2>&1 & echo $!");This works fine most of the time however is rather unpredictable. Is there a better/more solid way to achieve this?Thanks,Matt
|
Curl alternative to Cron Job PHP
|
Try adding dwc_otg.fiq_fsm_mask=0x3 to /boot/cmdline.txt and restart the device.
|
I'm trying to get a picture from webcam on Raspberry Pi every minute. So I wrote a script:NOW=$(date +"%H-%M-%S")
fswebcam -r 640x480 /home/pi/$NOW.jpgWhen I run it form command line like/home/pi/webcam_script, it works just fine. Then I add a task to cron usingcrontab -e:0-59 * * * * /home/pi/webcam_script >> cronlog 2>&1As a result, no pictures are captured. Incronlogfile I see the following error message:Error selecting input 0
VIDIOC_S_INPUT: Device or resource busySo, what is wrong and how can I automatically get pictures from a webcam
|
fswebcam cron: Device or resource busy
|
For MySQL you can try withnodejs-persistable-schedulerIn other cases you need to build your own solution. For example, I created a collection/table to store the schedule state and rules. Then, if the service's crashes or restarted, I can get all the schedules form the database and restart them again from theapp.listen event.
|
From what I have read, onlyAgenda,Node-crontabandschedule-droneprovide this feature. It would be grateful if you provide a small description of the mechanism which these library use for persistent storage of jobs.I need to send emails by reading the mail options fromMongoDBand want mynodeJSapplication to somehow schedule and be in sych with these even if nodeJS is stopped temporarily.
|
Which all libraries for NodeJS provide persistent scheduling and cron jobs
|
If you are willing to retain same cron expression, but give contextual calculations based on date timezone (so that user and serverside get next execution based on their timezones for same expression), you may usecron-utils, which provides such functionality. All next/previous execution calculations are contextual to timezone, since release 3.1.1.They provide an example at the docs://Get date for last execution
DateTime now = DateTime.now();
ExecutionTime executionTime = ExecutionTime.forCron(parser.parse("* * * * * * *"));
DateTime lastExecution = executionTime.lastExecution(now));
//Get date for next execution
DateTime nextExecution = executionTime.nextExecution(now));nextExecution value will be calculated for same timezone as reference date (now).
|
I am looking for a way to convert cron expression from one timezone to another one timezone.For example, my web-client user is GMT+1200 and my server-side is GMT+0800, while user setting 02:10 to execute task every Tuesday and Thursday, the cron expression will be0 10 2 3,5 * ?, and I have used code as below, it can get current fire time for user's timezoneCronExpression expr = new CronExpression("0 10 2 3,5 * ?");
System.out.println(expr.getNextValidTimeAfter(new Date()));
System.out.println(expr.getTimeZone());
System.out.println(expr.getExpressionSummary());
System.out.println("=======");
TimeZone tz = TimeZone.getTimeZone("GMT+1200");
expr.setTimeZone(tz);
System.out.println(expr.getNextValidTimeAfter(new Date()));
System.out.println(expr.getTimeZone());
System.out.println(expr.getExpressionSummary());ThegetNextValidTimeAfterwill printMon Feb 02 22:10:00 CST 2015, which aftersetTimeZone(tz);, however thegetExpreesionSummaryor evengetCronExpression()will still be0 10 2 3,5 * ?, where I want to get string will be0 10 22 2,4 * ?and then I can save into DB for next time fire and also another time-zone user to query setting (of course this will need to convert0 10 22 2,4 * ?to this user's timezone)Any help is appreciated
|
Convert cron expression from one timezone to another one
|
) Select records2) Loop over records3) start transaction (optional)4) Insert records in db25) Update records in db16) commit
|
i'm developing a webshop with a MySQL database for a client.
This client already invoice management website with a MySQL database.Now I want to write a php script thats triggered by a cronjob to sync invoice, client and product records.order record:id | clientId | status | shipping | reduction*order_items records:*id | productId | price |amount | orderIdclient record:id | fname | name | email | ...Note that only order records withstatus = 2should be synchronised, after they have been synchronised, the status should change to3.Both databases are using different tables for orders and invoicesWhat is the best way to do this?
|
How do I synchronise two MySQL databases using a Cronjob PHP script?
|
You should be able to use the following:at now /cron/monthly_save
|
I have a job scheduled by cron: popping emails from server every hour.But sometimes I don't want to wait for 60 minutes to check my emails. To do it, I use a script which run the same command I have in crontab. It is essentially as running the cron before it was scheduled tor run. Is it possible to run cron at particular time without changing it's settings?
|
Run cron now without changing its settings
|
Create a shell script and put the PHP command in there. Make it executeabl and put it into the crontab.You can then better track and change the command as well as setting up the environment (vars, paths) for the php script more easily.
|
Here's my situation:I'm trying to run a php script via cron, and I've got a crontab (/etc/crontab) that looks like this:SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/var/www:
MAILTO=<myemailaddress>
m h dom mon dow user command
* * * * * root /usr/bin/php /var/www/testing.phpAnd when I run the command/usr/bin/php /var/www/testing.phpfrom bash/sh, everything is dandy. It's just a basic php script that writes some gibberish to a file. However, my cronjob is not executing. I've used sudo service cron restart several times but all to no avail. Am I missing something obvious here?Thanks, and cheers!SolutionMy own fault! The php script I was running was writing to a file that was not properly accessed - e.g., lacking full file paths. Thanks for the help all!
|
Cronjobs not executing php scripts, no mailto warnings received!
|
-1If the command works outside of cron, but not in the crontab, the problem is almost certainly that the command isn't picking up some necessary environment variable setting. There are several ways to get around the problem, but the simplest and best is towrap your command in a shell script.For initial testing, you can simply source your login environment:. ~/.bash_profileBut eventually you'll want to just set the variables you need and not include anything extra. For more information, seeDefine your own job types.
|
I am trying to run a cron-task using Rails schedule.rb file. The task invokes a function written in ruby. The function runs perfectly fine. However when trying to run as a cron I get this error.Starting Spring server with `/home/ubuntu/.rvm/gems/ruby-2.4.0/gems/spring-2.0.2/bin/spring server --background` timed out after 20 secondsSpring(2.0.2) is installed and working perfectly.
Any idea how to solve this?
|
Spring server: Timeout error
|
The following command seems to work for me.0 8 ? * MON#2Assuming that you want this job to execute at 8 AM the second Monday of each month, the # character allows you to specify the "nth" day of any given month. We use the ? character in the day/month row since we are fine with any numeric day as long as it is the second Monday.Read more about special characters here:http://www.quartz-scheduler.org/documentation/quartz-2.2.2/tutorials/crontrigger.html#special-characters
|
I am trying to create recurring job in hangfire that runs, once a month at the second Monday, something like this:1. Monday, May 14, 2018 8:00 AM
2. Monday, June 11, 2018 8:0 AM
3. Monday, July 9, 2018 8:00 AM
4. Monday, August 13, 2018 8:00 AM
5. Monday, September 10, 2018 8:00 AMI have foundthisanswer in stackoverflow, but since this is not a standard cron for scheduling hangifre jobs I can not use it.My question is can I make an expression like this using the format* * * * * (min hour day/month month day/week)
|
Cron Expression for every second Monday of the month (for Hangfire)
|
See code below. Replace my print statements with what you want to show.import sys
if sys.stdout.isatty():
print "Running from command line"
else:
print "Running from cron"
|
I have a script and it's display show's upload progress by writing to the same console line. When the script is run from a cron job, rather than writing to a single line, I get many lines:*** E0710091001.DAT *** [0.67%]
*** E0710091001.DAT *** [1.33%]
*** E0710091001.DAT *** [2.00%]
*** E0710091001.DAT *** [2.66%]
*** E0710091001.DAT *** [3.33%]
*** E0710091001.DAT *** [3.99%]
*** E0710091001.DAT *** [4.66%]
*** E0710091001.DAT *** [5.32%]
*** E0710091001.DAT *** [5.99%]
*** E0710091001.DAT *** [6.65%]
*** E0710091001.DAT *** [7.32%]
*** E0710091001.DAT *** [7.98%]
*** E0710091001.DAT *** [8.65%]
*** E0710091001.DAT *** [9.32%]
*** E0710091001.DAT *** [9.98%]
*** E0710091001.DAT *** [10.65%]
*** E0710091001.DAT *** [11.31%]
*** E0710091001.DAT *** [11.98%]
*** E0710091001.DAT *** [12.64%]
*** E0710091001.DAT *** [13.31%]
*** E0710091001.DAT *** [13.97%]
*** E0710091001.DAT *** [14.64%]
*** E0710091001.DAT *** [15.30%]
*** E0710091001.DAT *** [15.97%]
*** E0710091001.DAT *** [16.63%]
*** E0710091001.DAT *** [17.30%]
*** E0710091001.DAT *** [17.97%]
*** E0710091001.DAT *** [18.63%]I just want to know if I can tell from inside the script if it's being called from cron, and if so, I won't display this output.
|
How can I tell if my script is being run from a cronjob or from the command line?
|
r0ast3d has a quick, clear answer - I did have to do some more searching to get each step done so I'll elaborate on his steps:Write a shell script to invoke your java program with the necessary arguments.
Example:!/bin/bash
echo "Running script."
cd ~/your/classpath/to/java
java -classpath .:somejar.jar path/to/your/ProgramSeparate your necessary classpaths with colons (:) rather than semicolons (;)
The path to your program should start with your package (find this at the top of the java program)Make sure that the classpath argument points to the jars that you need.
You can check your import statements in your java program to make sure you are specifying all the necessary classpaths. You have to run this script from your java directory, and can use a single period (.) as your first classpath argument.Make sure that the shell script has necessary unix permissions.Run from a terminal:sudo chmod ### yourScript.shWhere ### are numbers representing the correct permissions for your system setup.Schedule the script to be invoked by setting up a cron job.Run from a terminal:crontab -eThis will open your crontab editor. You can add a job in this way:*/5 * * * * bash /home/scripts/yourScript.shReplace the path to the script with the correct location of your script. This job is set to run every 5 minutes. Seehttp://www.adminschoice.com/crontab-quick-reference/for a good reference on crontab.Hope this helps someone out!
|
I am using a java program which sends email after finishing up some file transfers.I am using Eclipse to code up the program. How do I set up a cron job to execute this java program for a particular time. Also I have various jar files inside the project. Please suggest
|
Cron job for a Java Program
|
Running your program from a wrapper script as others have suggested is probably my preferred method, but there may be a few other solutions:If you're using a modern cron you may be able to do something like this in your crontab entry:* * * * * CARSPATH=/opt/carsi xreplacing the asterisks with the appropriate schedule designators.This will set CARSPATH for the x process and allow the use lib statement that passes the environment variable to work.You can also, depending on your shell and cron implementation, store your environment setup in a file and do something like:* * * * * source specialenv.sh && xWhere specialenv.sh contains lines like (for bash)export CARSPATH=/opt/carsiYou may also be able to set environment variables directly in the crontab, should you choose to do so.
|
I have a bunch of Perl scripts that all run fine, yet need to haveuse Plibdata;up top.I set up a cron job that runs (I get the confirmation email from root) and it spits back the following error message:Can't locate Plibdata.pm in @INC (@INC contains: /install/lib /opt/perl58/lib/5.8.8/IA64.ARCHREV_0-thread-multi /opt/perl58/lib/5.8.8 /opt/perl58/lib/site_perl/5.8.8/IA64.ARCHREV_0-thread-multi /opt/perl58/lib/site_perl/5.8.8 /opt/perl58/lib/site_perl .) at ./x line 5.
BEGIN failed--compilation aborted at ./x line 5.Line 5 is... you guessed it....use Plibdata;I am also attempting to set the environment as such:use lib "$ENV{CARSPATH}/install/lib";so maybe if I found the location of this plibdata, I could explicitly direct it that way?My cron commands will be executed using/usr/bin/shsays crontabs...Any suggestions?This script works from the command line.
|
Why can't my Perl script load a module when run by cron?
|
In case anyone else is interested,In the new CakePHP 2.0.5, you will an index.php in webroot folder:Copy this file and name it cron_dispatcher.php, and place it into the same directory (webroot)You will find this code at the very bottom:$Dispatcher = new Dispatcher();
$Dispatcher->dispatch(new CakeRequest(), new CakeResponse(array('charset' => Configure::read('App.encoding'))));change the bottom todefine('CRON_DISPATCHER',true);
$Dispatcher = new Dispatcher();
$Dispatcher->dispatch(new CakeRequest($argv[1]), new CakeResponse(array('charset' => Configure::read('App.encoding'))));You're doing two things here: Setting CRON_DISPATCHER to true, and passing environment variables ($argv[1]).In your controller, add this line before you do anything else:if (!defined('CRON_DISPATCHER')) { $this->redirect('/'); exit(); }This will ensure people going to yoursite.com/controller/cronaction won't be able to run your script.In your htaccess file in webroot, add this:<Files "cron_dispatcher.php">
Order deny,allow
Deny from all
</Files>This will ensure poeple going to yoursite.com/cron_dispatcher.php won't be able teo run it.Now set up the cron job using something like the command:php /home/yoursite/public_html/cakephp/app/webroot/cron_dispatcher.php /controller/cronjobaction
|
I am using CakePHP 2.0 and have been trying to setup a cronjob to execute a method in a controller. I've been going nuts, looking over various tutorials and random sites to see if I could find a solution.The error I am receiving is this:Undefined variable: argc [APP/webroot/cron_dispatcher.php, line 83Here is the bottom of the cron_dispatcher.php file in myapp/webroot/directory.if (!include(CORE_PATH . 'cake' . DS . 'bootstrap.php')) {
trigger_error("CakePHP core could not be found. Check the value of CAKE_CORE_INCLUDE_PATH in APP/webroot/index.php. It should point to the directory containing your " . DS . "cake core directory and your " . DS . "vendors root directory.", E_USER_ERROR);
}
if (isset($_GET['url']) && $_GET['url'] === 'favicon.ico') {
return;
} else {
define('CRON_DISPATCHER',true);
if($argc >= 2) {
$Dispatcher= new Dispatcher();
$Dispatcher->dispatch($argv[1]);
}
}I cannot find where these variables ($argv and $argc) are defined. They aren't defined anywhere in the dispatcher.php file itself. I searched Google to no avail. I'm not 100% sure how the Dispatcher works, but any help would be greatly appreciated. Thanks.== UPDATE
GoDaddy's shared hosting doesn't allow you to change the settings of argc argv.
|
Cron Dispatcher CakePHP 2.0
|
You might be able to fill in the command field with something like:do_something & sleep 30 ; do_somethingThe&runs the first command in the background, which lets the second command run at 30 seconds after the minute, not 30 seconds after the first command finishes.I'm not familiar with the cron interface shown in the image in your question, but if you have the ability to run arbitrary commands in a cron job, you can do just about anything you could do with shell access (just not as conveniently).
|
I want to run a command on host in less that a minute (for example every 30 second) but I don't have access to ssh.
all I have is.
I don't know how to do some hacking with this to run a code in less than a minute.EDIT1: in this question, I have limited access and I can't run every code(suggested in other questions) in terminal because I don't have access to terminal
|
run cron less than a minute in host
|
Is crond running?$ systemctl status crond
* crond.service
Loaded: not-found (Reason: No such file or directory)
Active: inactive (dead)If not try to start it before debugging any further. If you have not configured sudo then use root privileges by some other means, such as logging in as root or via su command.$ sudo systemctl start crond
|
I tried to set up a schedule to remove the old file and folder after several days. I put the following code in a script file and tried to use crontab to run it every day. The find command worked fine. but the crontab seems not execute the script file.I also use crontab for other tasks, i.e. rsync, they all work fine. I am wondering what might be the possible reason that crontab won't work in this case. And what could I do alternatively for the job? Thanks!#!/bin/bash -x
find /media -type d -ctime +18 | xargs rm -rfmy crontab entries are10 09 * * * /root/rsync-shell.sh &
20 09 * * * /root/chg3gp2avi.sh &
30 09 * * * /root/clean_files_10days.sh &the first two are the ones I set up before and work fine. The third one is the current one that won't work.
|
crontab not working under arch linux
|
Cron Jobs in ChefChef includes a resource for setting up Cron jobs - it's calledcron.cron 'test' do
minute '*/2'
command 'sh -x /var/test.sh > /var/log/backup 2>&1'
endBut what is your ultimate goal? Log rotation?Log Rotation with Chef and LogrotateThere is a tool for that, calledlogrotateand there is a Chef cookbook for that:logrotate.This gives you a resource that allows to to specify, which logs you want to rotate and with what options:logrotate_app 'test' do
path '/var/log/test/*.log'
frequency 'daily'
rotate 30
endJust in case you want to implement such a thing ;-)
|
All,I have a shell script that is creates tar file of logs. I have embeded the recipe in the cookbook.The recipe looks like this :cookbook_file "/var/create-tar.sh" do
source "create-tar.sh"
mode 0755
end
execute "create tar files of logs older than 1 day" do
command "sh /var/create-tar.sh"
endThe execute resource is executing the recipe. I want to schedule this shell script in cron by making an entry in cronjob.The crontab entry should be :*/2 * * * * sh -x /var/test.sh > /var/log/backup 2>&1How can I add this entry in my recipe?
|
How to add a cron job entry using Chef recipe
|
Assuming it's running in the background, under your user id: usepsto find the command's PID. Then usekill [PID]to stop it. Ifkillby itself doesn't do the job, dokill -9 [PID].If it's running in the foreground, Ctrl-C (Control C) should stop it.Read the documentation on thepscommand and familiarize yourself with its options. It's a very useful command.
|
I ran a php script, let's use "mytestscript.php" for example.It will run continuously for a few hours. How can I stop it from the Terminal (UNIX) command line?
|
How do I stop a script running in UNIX?
|
I guess this is a confirmation, the source code of theweekdays()method:public function weekdays()
{
return $this->spliceIntoPosition(5, '1-5');
}You can find it here:\vendor\laravel\framework\src\Illuminate\Console\Scheduling\Event.phpRight afterweekdays()you will seemondays()method, which shows that Laravel counts mondays as "day 1":public function mondays()
{
return $this->days(1);
}
|
I am writing Laravel scheduler task and want to run it once a day every weekday (From Monday to Friday).I see thatTask Schedulerhas->weekdays()option, that presumably does precisely what I want.
But I wasn't able to find a confirmation or description of this option that says it will run from Monday to Friday and not, say, from Monday to Saturday.Also I would like to run the task at specific time. I see there is a->dailyAt('13:00');method. I'd like to know the best solution to run task at weekdaysAt.Thanks in advance!P.S. I use Laravel 5.2, in case that matters.
|
Laravel Scheduler: how to run task on weekdays only?
|
The intent of this questions was not about CRON, but task scheduling in general using cron as an example, sorry if this was not clear in the question statement.I wanted to know how the the lowest level software does time-based scheduling, if it must poll the hardware clock or if there is some sort of hardware interrupt for time based events.It turns out there is actually a hardware interrupt. From wilipedia:One typical use is to generate interrupts periodically by dividing the
output of a crystal oscillator and having an interrupt handler count
the interrupts in order to keep time. These periodic interrupts are
often used by the OS's task scheduler to reschedule the priorities of
running processes. Some older computers generated periodic interrupts
from the power line frequency because it was controlled by the
utilities to eliminate long-term drift of electric clocks.http://en.wikipedia.org/wiki/InterruptSo, although cron does polling (thanks @joshua-nelson), it is possible not to and the OS does not.
|
When a task scheduler (e.g. cron) fires a tasks (e.g. cron jobs), does it do so by "polling" the clock every minimum period (e.g. second) or does it registers a callback that gets "pushed" when the time comes?If it is push/callback, how does the underlying platform (e.g. linux) does it? Is there a "hardware interrupt", or another callback mechanism, for time based events?So, how does a task scheduler fire a job?
|
How does a task scheduler fire a job?
|
You need to setup your crontab with rvm e.g:rvm cron setupWith that rvm sets your environment variables in your crontab filethen you have a crontab file having this at the top:PATH="/usr/local/rvm/gems/ruby-1.9.3-p194/bin:/usr/local/rvm/gems/ruby-1.9.3-p194@global/bin:/usr/local/rvm/rubies/ruby-1.9.3-p194/bin:/usr/local/rvm/bin:/usr/local/rvm/gems/ruby-1.9.3-p194/bin:/usr/local/rvm/gems/ruby-1.9.3-p194@global/bin:/usr/local/rvm/rubies/ruby-1.9.3-p194/bin:/usr/local/rvm/bin:/usr/lib64/qt-3.3/bin:/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin:/usr/local/rvm/gems/ruby-1.9.3-p194@global/"
rvm_env_string='ruby-1.9.3-p194'
rvm_path='/usr/local/rvm'
rvm_ruby_string='ruby-1.9.3-p194'
RUBY_VERSION='ruby-1.9.3-p194'
GEM_HOME='/usr/local/rvm/gems/ruby-1.9.3-p194'
GEM_PATH='/usr/local/rvm/gems/ruby-1.9.3-p194:/usr/local/rvm/gems/ruby-1.9.3-p194@global'
MY_RUBY_HOME='/usr/local/rvm/rubies/ruby-1.9.3-p194'
IRBRC='/usr/local/rvm/rubies/ruby-1.9.3-p194/.irbrc'Then you can stick your crontask beneath it
|
I'm trying to run a cron job using Gems. I've installed ruby via RVM and when I require a gem it breaks the cron job. I've tried requiring two totally different gems, PG / Pry, and when I require either, the cronjob doesn't complete. Here is the "testing code" that works fine:open('/home/log.log', 'a') do |f|
f.puts Time.now.to_s
endHere is how I setup the cronjob:* * * * * /usr/local/rvm/rubies/ruby-2.0.0-p247/bin/ruby /home/test1.rbI can see new output every minute. And when I add a require gem line at the top, it then breaks, but only when run through cron:require 'pg'
open('/home/log.log', 'a') do |f|
f.puts Time.now.to_s
endThe cronjob runs (I can see it execute in the sys log), but never completes (no output ever makes it into the text file). I've tried this on two separate servers one Debian, one CentOS, and both have the same issue. Oddly enough this only affects the cron job, if I run the same ruby file from console: /home/test1.rb it will work just fine.Any help would be great.
|
Requiring a Ruby Gem in Ruby Script breaks Cron Job Execution
|
At nowadays you can schedule php script execution from UI like this:In case you still need execute script via command line pay attention that Plesk's PHP binaries are placed in:# 7.0
/opt/plesk/php/7.0/bin/php
# 5.6
/opt/plesk/php/5.6/bin/php
# 5.5
/opt/plesk/php/5.5/bin/php
# and so onOriginal answer:I know this is a few months old, but for the next person that comes across a problem while using Plesk and cron and PHP, here's the answer.While Plesk does run cron as ROOT, it also runs PHP by default with safe mode ON, which means that when you setup a cron in Plesk that needs PHP, it's going to have restrictions that you do not experience from the shell or from the web.So what you do is use the CLI /etc/php.ini option override, like so:/usr/bin/php -q -d safe_mode=Off /var/www/vhosts/path-to-your-php-file.php
|
I'm using the Kohana framework (3.0.9), which generates daily logs. I want to mail the log file if one was made the day before CRON runs the script, but after days trying I can't figure out how to put off safe_mode in PHP CLI modus.When I'm running my script on the web, there is no problem. But I want to run the script as a CRON task on my Plesk 9.5.2 server (or on the command line as root user) I'm getting the following error:ErrorException [ 2 ]: dir(): SAFE MODE Restriction in effect. The script whose uid is 10001 is not allowed to access /var/www/vhosts/mydomain.com/subdomains/mysubdomain/httpdocs/application/logs/2011/01 owned by uid 48 ~ APPPATH/classes/controller/ajax.php [ 181 ]I've allready put SAFE MODE off in my Plesk control panel, which works fine for the web request, but not in on the command line or as an CRON task.I'm using the following code to test if its working:$d = dir(APPPATH.'logs/2011/01/');
echo "Handle: " . $d->handle . "\n";
echo "Path: " . $d->path . "\n";
while (false !== ($entry = $d->read())) {
echo $entry."\n";
}
$d->close();I can read the directory APPPATH.'logs/', and also the directory APPPATH.'logs/2011', but the directory's representing each month with the daily log files always give an error.
|
PHP cli command line safe_mode restriction
|
You could use a second cron job at 09pm to start a second program that tells the first program to terminate.There are a number of ways to do this. One of the easiest might be to have the second program touchterminate.txtin a convenient place. On each loop of the first program, it could check for this file. If it exists, it could delete the file and gracefully exit.
|
Is it possible to setup a cron job to work on certain days only at night, for example, the first day of each month from 03pm to 09pm?I want to do an email campaign only at night when the server load is low.Is it possible to run a cron job at a certain time and stop it at a certain time?
|
Cron job start and stop at certain time
|
Log in to your system via SSH, and then enter,crontab -eIf this is your first time editing, it may ask you what editor you would like to use.
Then start editing.*/1 * * * * /var/www/mysite/public/cron/script.phpWill run script.php every minute.
|
I have thought of using cron jobs recently. In my site, I havecss,jsandimagesfolders in my setup, which isn't very relevant, but might be needed.I know how to do a cron job, but am unsure as to where to put it in my files so that it always runs every day.So where should I put the cron job file, should I create a new folder for it and what should the file extension be?
|
Where to store Cron Jobs, and will they always run?
|
Command to run a PHP 7.0 cron job:/opt/cpanel/ea-php70/root/usr/bin/php /home/username/public_html/myjob.php >> /home/username/myjob.logCommand to run a PHP 7.1 cron job:/opt/cpanel/ea-php71/root/usr/bin/php /home/username/public_html/myjob.php >> /home/username/myjob.logCommand to run a PHP 7.2 cron job:/opt/cpanel/ea-php72/root/usr/bin/php /home/username/public_html/myjob.php >> /home/username/myjob.log
|
I want to setup cron job on cpanel admin with php7 version. My php script for cron requires php 7.0 or above to run. The problem is that the path to php7 cannot be found. I have already selected php 7.0 as current version in cpanel. I do not have access to ssl.what I have done is similar to this this/usr/local/cpanel/3rdparty/bin/php "/home/username/public_html"/myjob.php >> "/home/username"/myjob.logThis works for scripts which runs with php 5.6 but my problem is that the jobmyjob.phprequires php 7.0. I tried to run withphp7,php70,php7.0but none run. I tried to run like this./usr/local/cpanel/3rdparty/bin/php7 "/home/username/public_html"/myjob.php >> "/home/username"/myjob.logMy problem is that I cannot find the the path to php7. Where is the path to this version? How can I run this?
|
Run cron job on cpanel with php7 version
|
According to your description, if you want to created a scheduled WebJob which will fired at 8:00 AM.I suggest you could try to use below cron.At 8:00 AM every day: 0 0 8 * * *More details about how to set the cron, you could refer to thisarticle.Result:Besides, if you want to make sure your web jobs will continue worked. I suggest you should enable the "Always On" setting to be enabled on the app.About how to enable it, you could refer to below steps:Notice: This technique is available to Web Apps running in Basic, Standard or Premium mode
|
I actually require an cron expression to automatically restart an app at 8 am every day. for that I have to create an scheduled webjob in azure but i'm not getting the exact cron expression.
|
cron expression to run a webjob at 8 am everyday in azure
|
First of all create acustom admin command. This command will be used to add the task to the crontab. Here is an example of my custom command:cron.pyfrom django.core.management.base import BaseCommand, CommandError
import os
from crontab import CronTab
class Command(BaseCommand):
help = 'Cron testing'
def add_arguments(self, parser):
pass
def handle(self, *args, **options):
#init cron
cron = CronTab(user='your_username')
#add new cron job
job = cron.new(command='python <path_to>/example.py >>/tmp/out.txt 2>&1')
#job settings
job.minute.every(1)
cron.write()After that, if you have a look at the code below, a python script is going to be invoked every 1 minute. Create anexample.pyfile and add it there the functionality that you want to be made every 1 minute.All is prepared to add the scheduled job, just invoke the following command from the project django directory:python manage.py cronTo verify that the cron job was added successfully invoke the following command:crontab -lYou should see something like this:* * * * * <path_to>/example.pyTo debug the example.py, simply invoke this coomand:tail -f /tmp/out.txt
|
I've searched the internet for a working example of a scheduled job in Django. But I can only find how to do it, but no example is given. Can someone share a working example of the Django framework running a scheduled task with cron?
|
Example Cron with Django
|
When you invoke a script with nodejs, it appears in the process list such as:user 773 68.5 7.5 701904 77448 pts/0 Rl+ 09:49 0:01 nodejs scriptname.jsSo you could simply checkpsfor its existence with a simple bash script:#!/bin/bash
NAME="scriptname.js" # nodejs script's name here
RUN=`pgrep -f $NAME`
if [ "$RUN" == "" ]; then
echo "Script is not running"
else
echo "Script is running"
fiAdjust it up to your needs and put into cron.
|
Read as:Detect (if specific node.js script is running) from bash.I have a server that runs a specific node.js script on certain actions and certaincronintervals.The script might take a few hours to finish, but is not supposed to run more than once at the same time.Is there a way inshorbashto detect if the specific script is already running?processSimply running (if)pidof nodewon't work, because there might be other unrelated node scripts running.pidfileThe closest half solution I can think of istouch /tmp/nodescript.lockand only run the script if it does not exist. But apparently/tmpdoesn't (always) get cleaned on a server crash/reboot.secret option number 3Perhaps there's some other simple way I'm not aware of. Maybe I can give a process some kind of static identifier, which is gone when the process is. Any ideas?
|
Detect if specific node.js script is running from bash
|
If you use a date format likedate +"%d-%m-%Y_%H:%M"in your crontab you may need to escape the%characters with a backslash, like this:date +"\%d-\%m-\%Y_\%H:\%M".Many crons handle%specially by replacing them with newline and sending the following text as stdin to the command before it. Seeman 5 crontabfor details.
|
I'm running a cron every 6 hours to backup my database.
I want the filename to contain the date & time it was created in the following format:mysqlbackup_22/5/2013_15:45.sql.gzThis is the command I run:date=`date -d`; mysqldump -uusername -ppassword dbname | gzip > /path/to/dir/mysqlbackup_$date.sql.gzWhat do I need to changedate -dto?
|
Date time format in UNIX crontab
|
I think rufus-scheduler is for those people who aren't comfortable using the system'scrontab,atorbatch.crondoes repeating/periodic jobs andatandbatchare for one-time jobs because those two commands don't support automatically repeating commands.So rufus-scheduler is creating the functionality of the other commands, but if you're comfortable at the command-line and with the other commands, it doesn't buy you much in my opinion.I haven't used it, but did look through the source, and my concern is that it appears rufus-scheduler relies on threads, which mean Ruby will keep your app running in the background, waiting for the appropriate time or interval to run. If the process gets killed, or the machine restarts it looks like the job won't run, which is a major difference compared to the system's commands which will persist across reboots or the app not being in memory.We use cron a lot at work for jobs; It's an industry standard tool, and every Linux and Mac computer is running cron-scheduled jobs all through the day, though most users don't know it.
|
https://github.com/jmettraux/rufus-schedulerstates that:rufus-scheduler is a Ruby gem for scheduling pieces of code (jobs). It understands running a job AT a certain time, IN a certain time, EVERY x time or simply via a CRON statement.rufus-scheduler is no replacement for cron/at since it runs inside of Ruby.so what if it runs inside ruby? can't i access cron using the system command in ruby?
|
what's the difference between rufus-scheduler and a cron?
|
You need to escape "%" characters in crontab entries with backslashes- see the crontab(5) manpage. I've had exactly the same problem.For example:0 7 * * * mysqldump usblog | bzip2 -c > usblog.$(date --utc +\%Y-\%m-\%dT\%H-\%M-\%SZ).sql.bz2Do you not get emails of cron errors? Not even if you put "[email protected]" in the crontab?You may also need to set PATH in your crontab if pg_dump or gzip isn't on the system default path (so use "type pg_dump" to check where they are, crontab usually only runs commands in /bin or /usr/bin by default)
|
I have an entry in my crontab that looks like this:0 3 * * * pg_dump mydb | gzip > ~/backup/db/$(date +%Y-%m-%d).psql.gzThat script works perfectly when I execute it from the shell, but it doesn't seem to be running every night. I'm assuming there's something wrong with the permissions, maybe crontab is running under a different user or something. How can I debug this? I'm a shared hosting environment (WebFaction).
|
How to test crontab entry?
|
My guess is that the usercronuse do not configure thePATHin the same way as your user, and do not knownodenornpm.What you can try is to use the commandwhich nodeto know where your node binary is (/some/path/to/node)Then you can use the absolute path in your crontab:0 * * * * /some/path/to/node /path/to/your/script.jsEDIT:The difference between addingnodeandnpmto$PATHand using absolute paths is that absolute path will work for one executable, since Linux will not have to search thePATH.
Adding to thePATHwill make Linux recognizenodeandnpmjust as in your user. The fact that they are in the same folder do not affect that.
|
I know that you can run a Node.js script in Crontab by doing something like:0 * * * * node /path/to/your/script.jsBut I want to run a Node.js app, not a script, using Crontab. I created a Node.js app in order to write some automated tests using Mocha, Chai and Selenium, and I want to run it periodically by using Crontab. How would I go about doing this? I currently run my app by writing in the command line:npm run api-proWhere api-pro is a script from my package.json that invokes some tests for the production api.Note that if I simply try to write a Crontab job with the command "npm run api-pro" it doesn't recognize the command npm (and obviously I do have Node installed in my computer).
|
Not able to use Node.js and Crontab
|
After further research I found that when I used ftp_pasv the problem did not occur. I assume that some server settings were changed without notification.ftp_pasv($conn_id, TRUE);
if (ftp_put($conn_id, $remote_file, $file, FTP_ASCII)) { ...
|
I am trying to download files to a server after the service provided updated their servers.
The login information is accurate.
I used a generic code to do this.
Example:<?php $file = $ROOT.$_GET['file'];
$ftp_server = "127.0.0.1";
$ftp_user_name = "user";
$ftp_user_pass = "pass";
// set up a connection or die
$conn_id = ftp_connect($ftp_server) or die("Couldn't connect to $ftp_server");
// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
if (ftp_get($conn_id, $file, $file, FTP_BINARY)) {
echo "Successfully written to $file\n";
} else {
echo "There was a problem\n";
}
?>I was able to contact the service providers but now they are telling me that ftp_get is outdatd or something like that. Is there something i can do on my end to resolve this?
|
PHP Warning: ftp_get(): Unable to build data connection: Connection timed out with scheduled task
|
You should know that there is no threads in PHP.
But you can execute programs and detach them easily if you're running on Unix/linux system.$command = "/usr/bin/php '/path/to/your/php/to/execute.php'";
exec("{$command} > /dev/null 2>&1 & echo -n \$!");May do the job. Let's explain a bit :exec($command);Executes /usr/bin/php '/path/to/your/php/to/execute.php' : your script is launched but Apache will awaits the end of the execution before executing next code.> /dev/nullwill redirect standard output (ie. your echo, print etc) to a virtual file (all outputs written in it are lost).2>&1will redirect error output to standard output, writting in the same virtual and non-existing file. This avoids having logs into your apache2/error.log for example.&is the most important thing in your case : it will detach your execution of $command : so exec() will immediatly release your php code execution.echo -n \$!will give PID of your detached execution as response : it will be returned by exec() and makes you able to work with it (such as, put this pid into a database and kill it after some time to avoid zombies).
|
In a apcahe server i want to run a PHP scripts as cron which starts a php file in background and exits just after starting of the file and doesn't wait for the script to complete as that script will take around 60 minutes to complete.how this can be done?
|
Multi threading in PHP
|
When you're running into problems like this it's almost always an environment issue.Dump the results of "env" to a file and inspect that. You can also run your script with top line of#!/bin/sh -xto see what's happening to all the variables. You might want to use a wrapper script so you can redirect the output this provides for analysis.
|
I have a script that updates a server with some stats once per day. The script works as intended when running from command line, but when running from cron some of the variables are not passed to curl.Here is an example of the code:#!/bin/sh
PATH=/bin:/sbin:/usr/bin:/usr/sbin
/bin/sh /etc/profile
MACADDR=$(ifconfig en0 | grep ether | awk '{print $2}')
DISKUSED=$(df / | awk '{print $3}' | tail -n1)
DISKSIZE=$(df / | awk '{print $2}' | tail -n1)
# HTTP GET PARAMS
GET_DELIM="&"
GET_MAC="macaddr"
GET_DS="disk_size"
GET_DU="disk_used"
# Put together the query
QUERY1=$GET_MAC=$MACADDR$GET_DELIM$GET_DS=$DISKSIZE$GET_DELIM$GET_DU=$DISK_USED
curl http://192.168.100.150/status.php?$QUERY1The result in the cron job ishttp://192.168.100.150/status.php?macaddr=&disk_size=&disk_used=I am not sure if it is some problem with the variables, or possibly with awk trying to parse data with no terminal size specified, etc.Any help is appreciated.
|
Shell script runs from command line, not cron
|
The difference between a cron job and a job run from the shell is 'environment'. The primary difference is that your profile and the like are not run for a cron job, so any environment variables you have set in your normal shell environment are not set the same in the cron environment - no extensions to PATH, no environment variables identifying where Delicious and/or WP are hosted, etc.Suggestion: create a cron job that simply reports the environment to a known file:env > /home/27632/tmp/env.27632Then see what is set in your own shell environment in comparison. Chances are, that will reveal the trouble.Failing that, other environmental differences are that a cron job has no terminal, and has /dev/null for input and output - so interactive stuff does not work well.
|
I have a perl script (which syncs delicious to wp) which:runs via the shell butdoes not run via cron (and i dont get an error)The only thing I can think of is that it read the config file wrongly but... it is defined via the full path (i think).I read my config file as:my $config = Config::Simple->import_from('/home/12345/data/scripts/delicious/wpds.ini',
\my %config);(I am hosted on mediatemple)Does anybody have a clue?update 1: HERE is the complete code:http://plugins.svn.wordpress.org/wordpress-23-compatible-wordpress-delicious-daily-synchronization-script/trunk/(but I have added the path as above to the configuration file location as difference)update 2: crossposted onhttps://forums.mediatemple.net/viewtopic.php?pid=31563#p31563update 3: the full path did the trick, solved
|
Perl script works but not via CRON
|
It's a good approach, but the most important thing you can do right now is have a clear interface for queuing up the messages, and one for consuming the queue. Don't make the usage on either end hard-coded to a DB.Later on, if this becomes a bottleneck, you may want the mail sending to be done from a different machine which may not even have access to the DB, so this tiny investment up front will give you options later.
|
I have a web application that currently sends emails. At the time my web applications sends emails (sending of emails is based on user actions - not automatic), it has to run other processes like zipping up files.I am trying to make my application "future proof" - so when there are a large number of users I don't want the server strained, so i thought that putting the emails that need to be sent and the files that need to be zipped in a queue. Put them in table and then use a cron job to check every second and execute them (x rows at a time).Is the above a good idea? Or is there a better approach? I really need help to get this done properly to save myself headaches later on :)Thanks all
|
Web Application Architecture: Future Proofing
|
I guess there were no suggestions, I've done this by writing this in web routesRoute::get('scheduler', ArtisanController@handle)->middleware('app-engine-cron');this inArtisanControllerclass ArtisanController extends Controller
{
public function handle()
{
shell_exec('php '.base_path('artisan').' schedule:run > /dev/null 2>/dev/null &');
}
}and this middlewareclass AppEngineCronMiddleware
{
public function handle($request, Closure $next)
{
if (!$request->hasHeader('X-Appengine-Cron')) {
return response()->json(trans('auth.unauthorized'), 401);
}
return $next($request);
}
}And finallycron.yamllike thiscron:
- description: "Laravel Scheduler"
url: /scheduler
schedule: every 1 mins
target: defaultAnyone having this issue, can try this, it is working for me as expected. Anyways other suggestions are very welcomed. Especially from Google
|
Is there any way to executephp artisancommands on App Engine?
I need to set up Laravel'sTask Schedulingwhich requires the following cron job to be set up:* * * * * php /path-to-your-project/artisan schedule:run >> /dev/null 2>&1but as I looked atcron.yamldocumentation, there is no method to execute php file, there seems to be support for only HTTP call to URL.Can anyway help me with this please?UPDATE 1Please do not suggest to callArtisan::handle($command)from within the controller. I need exactly PHP-CLI version ofartisan
|
Laravel Task Scheduling on Google App Engine
|
Your line incrontabshould probably be something along the lines of:* * * * * cd /home/labtec901 && /usr/bin/python /home/labtec901/program.pyThis fixes two issues: Your program is now running inlabtec901's home directory (instead ofroot's directory, if that's whose crontab it is), and the path to Python has been corrected - from/user/bin/pythonto/usr/bin/python.Alternatively, if you don't want thecdcommand in the crontab, just put is as the first lines of the python program:import os
os.chdir('/home/labtec901')OR, you can specify the absolute path of the file to open:playercountlog = open("/home/labtec901/PMCcount.txt", "a")
|
I wrote a python script which writes to a text file, with the code that looks like this:playercountlog = open("PMCcount.txt", "a")
playercountlog.write(time.strftime("%m/%d/%Y"));
playercountlog.write(" ");
playercountlog.write(time.strftime("%I:%M:%S"));
playercountlog.write(" ");
playercountlog.write(count);
playercountlog.write("\n")
playercountlog.close()This script works fine when executed as root (python program.py), but when added to cron like so:* * * * * /user/bin/python /home/labtec901/program.pynothing gets written to the file.I've chmodded both the program and the txt file to 777 just to be sure, but no difference. What gives?
|
Python writing to file works fine when done manually, but cron fails
|
bin/neo4j statusis the command you are looking for.
|
Is there any way to check whether Neo4J is running usingpidofcommand? I tried doingpidof /path/to/neo4j/bin/neo4jBut it didn't seem to work.I need it to set up a script that I will then launch with cron to make sure that if the database crashes I can restart it again.Thank you!
|
How to check if Neo4J is running on the server?
|
Put it incrontabas follows:0 0 * * 6 /path/to/perl A.plThis is, of course, assuming you're on Unix. I have no clue about Windows.
|
Under unix system ..I want to run a perl script A.pl in every Saturday. I tried the code below, it works. But I am wondering does there exists any other code can work but does not keep checking the time in a busy loop?while(1)
{
@Time = localtime();
if( $Time[6] eq "6" )
{
`perl A.pl`;
}
}
|
How to run a script at a specific time, like every Saturday?
|
The way GAE executes a cron job allows it to run for 10 min. This is probably done (i'm just guessing here) through checking the user-agent, IP address, or some other method. Just because you setup a cron job to hit a URL in your application doesn't mean a standard HTTP request from your browser will allow it to run for 10 minutes.The way to test if the job works is to do so on the local dev server where there is no limit. Or wait until your cron job executes and check the logs for any errors.Hope this helps!
|
According tohttps://developers.google.com/appengine/docs/python/config/croncron jobs can run for 10 minutes. However, when I try and test it by going to the url for the cron job when signed in as an admin, it times out with a DeadlineExceededError. Best I can tell this happens about 30 seconds in, which is the non-cron limit for requests. Do I need to do something special to test it with the cron rules versus the normal limits?Here's what I'm doing:Going to the url for the cron jobThis calls my handler which calls a single function in my py scriptThis function does a database call to google's cloud sql and loops through the resulting rows, calling a function on each row that use's ebay's api to get some dataThe data from the ebay api call is stored in an array to all be written back to the database after all the calls are done.Once the loop is done, it writes the data to the database and returns back to the handlerThe handler prints a done messageIt always has issues during the looping ebay api calls. It's something like 500 api calls that have to be made in the loop.Any idea why I'm not getting the full 10 minutes for this?Edit: I can post actual code if you think it would help, but I'm assuming it's a process that I'm doing wrong, rather than an error in the code since it works just fine if I limit the query to about 60 api calls.
|
If Google App Engine cron jobs have a 10 minute limit, then why do I get a DeadlineExceededError after the normal 30 seconds?
|
The cron executes the PHP not like a module of apache, so many environment variables are not set by the server. When executing from cron your PHP script is like GCI one, more precisely its CLI (command line interface - php-cli). So as you can imagine, there is no web server and there is no HTTP_HOST.PS: You can transfer data (urls, hostname or whatever you like) as command line arguments (environment variables) to PHP:Command line usageAddition:$php -f cronjob.php HTTP_HOST=www.mysite.com #example
<?php
// cronjob.php
$host = $_GET['HTTP_HOST']; // Get the host via GET params
?>
|
I am using Facebook SDK to post some test wall post on my own facebook page. It works fine when i run the script on my browser but when i run it from terminal it gives me as error as below, i don't know what's wrong please help. I want to post on my facebook page using php CRON scripts like every 6 hours.Undefined index: HTTP_HOST error in Facebook/src/base_facebook.php
|
Why am i getting Undefined index: HTTP_HOST error?
|
Change the cron command to something likephp myJob.php >> stdout.log 2>> stderr.logThis should redirect the regular output tostdout.logand the errors tostderr.log.
|
I've got a script that PIPES an email address but it's not doing what I need it to do and I believe it's returning some php FATAL errors. I have it setup to log some responses already and write the responses to a .html file however how do I get the FATAL errors to log in that same .html file so I can debug my script?
|
how to see php errors returned in a cron job
|
Look for mail that the cron daemon might have sent to the user under which the cron job is running. If a cron job produces output on stderr or stdout, the cron daemon will email that to the owner of the cron job. If something is going wrong (possibly because of a PATH issue, like Rob suggests above), you might see a helpful error message in an email from the cron daemon.
|
When I execute a rake task manually, it works fine but when I put the same command in Cron nothing happens:cd /path/to/my/rails/app && rake daily_importThe Cron log indicates that the command was issues:CMD (cd /path/to/my/rails/app && rake daily_import)The rake task logs error and success messages, but nothing is recorded to the log, nothing is done at all. However if I copy and paste the text of the CMD with the same user Cron is running the command in everything works fine.I'm assuming that running a task in Cron should be the same as typing it in myself, is this correct?
|
Ruby on Rails - Rake task not working through Cron
|
Let the cron job run after every minute and in yourphpscript the following code example might help you out. I have used counter limit to 6 because this script will run after every ten seconds and six times in one minute.<?php
for($i=0;$i<6;$i++){
sleep(10);
task();
}
function task(){
}
|
This question may seem repetitive, as there are many threads around with the same subject, but thing is that most solutions seems to be linked with terminal coding, which i'm not comfortable with. The problem is simple i have a php script that needs to be executed very 10 seconds. Cron job in cpanel allows only upto 1 minute. What's the workaround to let cron work every 10 seconds ?
|
Running a php script as a cron job every 10 seconds
|
To answer your question, I tried some google search but without any luck. Anyway, the best way to resolve an issue is EXPERIMENTINGSTEP#01Setup an testing job withgitas source Code Management method.STEP#02In theBuild Triggerssection, set this job toPoll SCMevery2 minutes.STEP#03Add anExecute Shellto set our testing job execute2.5 minutes.Now let's see what happened.Firstly, last Poll started at1:23:00 PMSecondly, latest build started on 1:24:00 PM and supposed to end at1:26:00 PMBut you can see, Poll started again at1:25:00 PMregardless the build was still running.So "Does Jenkins “SCM Poll” while a job is running?"The answer is "YES"
|
I have a Jenkins build triggered by a Perforce SCM Poll.Does the poll continue to happen even if the Jenkins job is running? Or does it only poll between jobs?
|
Does Jenkins "SCM Poll" while a job is running?
|
If you want the php solution, the simple way is to create a lock file, each time script is executed , check if file exist then exit script, if not let script go to end. But i think it's better to use flock in cron instruction ;)<?php
$filename = "myscript.lock";
$lifelimit = 120; // in Second lifetime to prevent errors
/* check lifetime of file if exist */
if(file_exists($filename)){
$lifetime = time() - filemtime($filename);
}else{
$lifetime = 0;
}
/* check if file exist or if file is too old */
if(!file_exists($filename) || $lifetime > $lifelimit){
if($lifetime > $lifelimit){
unlink($filename); //Suppress if exist and too old
}
$file=fopen($filename, "w+"); // Create lockfile
if($file == false){
die("file didn't create, check permissions");
}
/* Your process */
unlink($filename); //Suppress lock file after your process
}else{
exit(); // Process already in progress
}
|
I have a cron job that executes every minutes. But I discovered thats it's running multiple times. I'm looking for a way to check if the process is still running then don't start a new one, or terminate the already running process before starting a new one.
|
Check if a php file command is already running on cron
|
Please note here that all the gems are installed in default gemsetI had 3 gemsets available in production. Rails is usingdefaultone where all required gems are installed.As can be seen in the crontab list, crontab is also looking path inglobalgemset directory as well.So I just selectedglobalgemset and installbundler$ rvm gemset use global
$ gem install bundlerThese steps fixed the issue.
|
I have deployed application using Capistrano 3. I keep on getting following error.`require': cannot load such file -- bundler/setup (LoadError)Here is the cron tab listPATH=/home/deploy/magnificent/shared/bundle/ruby/2.2.0/bin:/usr/local/rvm/gems/ruby-2.2.2/bin:/usr/local/rvm/gems/ruby-2.2.2@global/bin:/usr/local/rvm/rubies/ruby-2.2.2/bin:/usr/local/rvm/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games
* * * * * /bin/bash -l -c 'cd /home/deploy/magnificent/releases/20150830045359 && bin/rails runner -e production '\''Document.process_pending'\'' >> log/cron_standard.log 2>> log/cron_error.log'andschedule.rbenv :PATH, ENV['PATH']
set :output, { error: 'log/cron_error.log', standard: 'log/cron_standard.log'}
every 1.minutes do
runner 'Document.process_pending'
endPlease note here that all the gems are installed indefaultgemset
|
Error running cron job `require': cannot load such file -- bundler/setup (LoadError)
|
A number of significant drawbacks:If you ever want to change the polling frequency (i.e. do it every 2 minutes, or every 10 minutes), you have to change the program. This is especially difficult if you have an irregular polling schedule, something like once every 5 minutes on Monday through Friday, but once every 15 minutes on Saturday and Sunday. Sure, you don'tthinkyour program will ever need to do that, but requirements evolve.As you say, killing the process is the only way to stop the program. And killing it in mid-process might be a bad thing. You could of course add some cancel logic, but that's additional development time.The program is occupying memory while it's sitting there doing nothing (most of the time). This is a waste of resources. Probably not a huge deal when you're working with a system that has many gigabytes of memory, but it becomes an issue when you're working on embedded systems with limited memory.You're wasting your time writing your own scheduling, which you then have to debug and maintain, when there's already a perfectly good scheduler built into the operating system.I call this program a "catnap program" because it acts just like a cat: it sleeps most of the time, waking up now and then to stretch and maybe bat a string around for a few minutes, and then goes back to sleep.Programs are not cats.
|
So I've had an idea in my head today... And I would like to hear some feed-back. I have a Java app which needs to check a directory every 5 minutes. Plain and simple the app needs to run every five minutes.Seems like a good candidate for cronjob, but I was wondering... why not keep the logic/timing all within the app like so (simplified obviously):public static void main(String[] args) {
while(true) { // repeatedly execute...
// do the work/job
Thread.sleep(600 * 1000); // make the thread sleep for 5 minutes
}
}One significant downside I see is "How do westopthis app once it starts? Deleting it?Are there any other significant draw-backs to this besides that one?Should I stop daydreaming and just use cron jobs?
|
Infinite loop + Thread.sleep replace cron job
|
Type the following command to enter cronjob:$ crontab -eTo get crontab to run a task every 10 minutes you could type as follow:*/10 * * * * /path_to_scriptSee additional read for it:Wikipediacron-every-5-minutescron job every 5 minutes starting from a specific time
|
I've been working on a project and I would so not like it to be taken by system crash.So I wrote a script to backup my whole project directory into Dropbox.But I had to run it every 10 min, if I could remember to do that.Question: any way to auto-it-up?
|
How to write bash script that autoruns every 10 min?
|
Try using the fully specified path to shutdown. date may be in the PATH in roots cron environment, /sbin may not be looked up.
|
I'm using a Raspberry Pi for a status display, but for whatever reason it gets incredabbly sluggish after a day or so of running so I wanted to reboot it every day so I setup a cron job to do that every morning at 8:50. But, it doesn't seem to be working. Is there anything special about using cron to do a reboot?This is my crontab for therootuser:# m h dom mon dow command
50 8 * * * shutdown now -r >> /var/log/cron.log
0,30 * * * * date >> /var/log/cron.logThe second line works just fine, but I can't seem to get the restart command to work. It doesn't even output anything to the log.
|
Using Cron to Reboot
|
It looks like/bin/shis used to invoke your cron tabs, so that they run in their own environment, that's the first process. Then/bin/shinvokes php to run your actual script, and php is your second process. There's nothing wrong with this.
|
I have crontab configured like this:*/2 * * * * php /home/ec2-user/myapp/myscript.php >> /home/ec2-user/myapp/log/myapp.log 2>&1When I execute ps aux, I see the following output:ec2-user 1296 0.0 0.0 2984 992 ? Ss 15:36 0:00 /bin/sh -c /home/ec2-user/myapp/myscript.php >> /home/ec2-user/myapp/log/myapp.log 2>&1 SHELL=/bin/sh HOME=/home/ec2-user PATH=/usr/bin:/bin LOGNAME=ec2-user USER=ec2-user
ec2-user 1299 0.3 3.7 91528 63612 ? S 15:36 0:16 /home/ec2-user/myapp/myscript.php SHELL=/bin/sh USER=ec2-user PATH=/usr/bin:/bin PWD=/home/ec2-user SHLVL=1 HOME=/home/ec2-user LOGNAME=ec2-user _=/usr/bin/phpTo me it looks like same process was started twice at the same time, process one with PID 1296, process two with PID 1299.Is that normal? Why two processes are in ps output instead of one?
|
Cron starts same process twice
|
It would be:0 55 23 1/1 * ? *There is a nice website exactly for your case:CronMakerCronMaker is a utility which helps you to build cron expressions.
CronMaker uses Quartz open source scheduler. Generated expressions are
based on Quartz cron format.
|
I am using Quartz for Scheduling my job in java. I have used "CronTrigger" for setting my time.
I want to fire my Job each day at 11:55 Pm in night. What should i write in the setCronExpression(" ") for having my Job Done. .??What i thought of the Code is:---CronTrigger trigger = new CronTrigger();
trigger.setName("runMeJob");
trigger.setCronExpression("0 55 23 * * ?");Is the above code correct or should i do some modifications in it????
|
Java Scheduler Quartz Cron Trigger Time Setting
|
If you want to break up the script, you can leave the weekly cron but instead of sending mails you can queue it into a database table. Then, using a second cron that run every 5 or 10 minutes, you can read the database mail queue (searching for max 50 or 100 rows) and if you find something, you send a chunk of emails...In general, this strategy (huge queue loading, smaller queue processing in chunks) allow you to split execution of large processes.
|
Id like to run a cron job once a week which runs a php script.The script will need to get all users from a database and run another script which sends each user an email with a report with data pulled from an external API.The problem is, there is a 100mb memory limit on every cron job. If there are thousands of users in my db and I need to retrieve lots of data from the external API I will soon exceed the memory limit.Is there a way to work around this by breaking up the php scripts? What would your strategy be?
|
Cron job limitations
|
A cron job is just a task that get's executed in the background at regular pre-set intervals.You can pretty much write the actual code for the job in any language - it could even be a simple php script or a bash script.PHP Example:#!/usr/bin/php -q
<?php
file_put_contents('output.txt', file_get_contents('http://google.com'));Next, schedule the cron job:10 * * * * /usr/bin/php /path/to/my/php/file > /dev/null 2>&1... the above script will run every 10 minutes in the background.Here's a good crontab tutorial:http://net.tutsplus.com/tutorials/other/scheduling-tasks-with-cron-jobs/You can also use cURL to do this depending on what request method you want to use:$url = 'http://www.example.com/submit.php';
// The submitted form data, encoded as query-string-style
// name-value pairs
$body = 'monkey=uncle&rhino=aunt';
$c = curl_init ($url);
curl_setopt ($c, CURLOPT_POST, true);
curl_setopt ($c, CURLOPT_POSTFIELDS, $body);
curl_setopt ($c, CURLOPT_RETURNTRANSFER, true);
$page = curl_exec ($c);
curl_close ($c);
|
I would like to set up a cron job which sends an http request to a url. How would I do this? I have never set up a cronjob before.
|
How would I use a cron job to send an HTML GET request?
|
Try putting your url in quotes :* * * * * /usr/bin/lynx -term=vt100 "http://abc.com/dir1/di2/script.php?action=add&config=xyz" >/dev/null 2>&1For the little explanation,&is a special character which put the process in the background, so you have to put the url in quotes, otherwise cron try to put the first part in the background and execute the second part.
|
I have the following cron job command:* * * * * /usr/bin/lynx -term=vt100 http://abc.com/dir1/di2/script.php?action=add&config=xyz >/dev/null 2>&1My PHP script does not recognize _GET['config'] and I get a "Cron Daemon" email message which seems to alert me that the crontab instruction is not correct.If I take out the 2nd _GET var I do not get the "Cron Daemon" email.Any thoughts or suggestions on how to define multiple query string items in a crontab job?BTW, I tried the URL Encode char for the ampersand and that did not work either.
|
Multiple Query String Items in crontab Job
|
Here's some code you could use to get you going:// set user to check
$strUser = "username";
$strPassword = "password";
// open
$hMail = imap_open ("{mail.yourdomain.com:143/notls}INBOX", "$strUser", "$strPassword");
// get headers
$aHeaders = imap_headers( $hMail );
// get message count
$objMail = imap_mailboxmsginfo( $hMail );
// process messages
for( $idxMsg = 1; $idxMsg <= $objMail->Nmsgs; $idxMsg++ )
{
// get header info
$objHeader = imap_headerinfo( $hMail, $idxMsg );
// get from object array
$aFrom = $objHeader->from;
// process headers
for( $idx = 0; $idx < count($aFrom); $idx++ )
{
// get object
$objData = $aFrom[ $idx ];
// get email from
$strEmailFrom = $objData->mailbox . "@" . $objData->host;
// do some stuff here
}
// delete message
imap_delete( $hMail, $idxMsg );
}
// expunge deleted messages
imap_expunge( $hMail );
// close
imap_close( $hMail );
|
So I'm trying to figure out how to send an email to an address for example,[email protected]and instead of the e-mail going to there it would be instead sent or forwarded to a script that I create to read the contents of the email and store the contents into a database. Any suggestions on how to do it in PHP?Thanks!
|
Processing incoming e-mail with PHP Script
|
Usually you can use commas to separate the cron minutes/hours etc. -0,10,20,30,40,50in your minute field (but I can't guarantee your admin will take it - I know Plesk does) and*in all others . The command is more tricky, but something like this should do/usr/bin/wget -q -t 5 --delete-after URL_TO_YOUR_CRONorphp PATH_TO_YOUR_PHP_FILE_ON_THE_SERVER
|
In my hosting i have a section for cron job like this:(source:site-helper.com)The PHP script is called "croned.php", which I want it to run every 10 minutes.What I will fill in every field?I tried but it didn't work.Note: the full path to the script is: /home/axelzd/domains/hellodom.com/public_html/croned.php
|
Cron command to run PHP script every 10 minute
|
Declaring variables inside your cron job is more explicit and easier to maintain : all you have to modify is contained in your cron job, and you don't need to transfer multiple files should you move it to another system.PATH=/usr/bin:/your/fancy/dir
MYAPPROOT=/var/lib/myapp
*/2 * * * * myappinpath
*/3 * * * * $MYAPPROOT/mylocalapp
|
When running a script with cron, any executable called inside must have the full path. I discovered this trying to runwondershaper, when many errors showed when it tried to call tc. So my question is, what's the proper way to overcome this problem?Possible solutions:cd to the executable folder and prepare symbolic links to any other called executable there (not sure if it works - low portability)use full paths in the script (it works - low portability across different distros)exporting a path variable with the needed paths inside the script (not sure if it works)Well, thanks in advance for anyone helping.
|
Proper way to run a script using cron?
|
As correctly pointed out in the comments, you need to provide the script file in order to execute it via yourCronJob. You can do that by mounting the file within avolume. For example, yourCronJobcould look like this:apiVersion: batch/v1beta1
kind: CronJob
metadata:
name: hello
spec:
schedule: "*/1 * * * *"
jobTemplate:
spec:
template:
spec:
containers:
- name: hello
image: busybox
imagePullPolicy: IfNotPresent
command:
- /bin/sh
- -c
- /myscript/test.sh
volumeMounts:
- name: script-dir
mountPath: /myscript
restartPolicy: OnFailure
volumes:
- name: script-dir
hostPath:
path: /path/to/my/script/dir
type: DirectoryExample above shows how to use thehostPathtype of volume in order to mount the script file.
|
I would like to run a shell script inside the Kubernetes using CronJob, here is my CronJon.yaml file :apiVersion: batch/v1beta1
kind: CronJob
metadata:
name: hello
spec:
schedule: "*/1 * * * *"
jobTemplate:
spec:
template:
spec:
containers:
- name: hello
image: busybox
imagePullPolicy: IfNotPresent
command:
- /bin/sh
- -c
- /home/admin_/test.sh
restartPolicy: OnFailureCronJob has been created ( kubectl apply -f CronJob.yaml )
when I get the list of cronjob I can see the cron job ( kubectl get cj ) and when I run "kubectl get pods" I can see the pod is being created, but pod crashes.
Can anyone help me to learn how I can create a CronJob inside the Kubernetes please ?
|
How to execute script shell in Kubernetes cronjob
|
I use the following to solve the issue.
Hope could be the help to otherschmod gu+rw /var/run
chmod gu+s /usr/sbin/cron
# Optional
# chmod g+s, u-s /usr/bin/crontab
crontab -u my_user /home/my_user/cron.txt
|
We use open-shift, and the docker container only could be run as non-root user.However, the cron failed start with error:seteuid: Operation not permittedI have already done the following settings, the error is still therechmod gu+rw /var/run
crontab -u my_user home/my_user/Base/cron.txt
usermod -a -G root,crontab my_userHow to avoid the error?
|
Run Cron as non root user
|
First of all, I imagine you are planning on adding code to your python script and that that is why you use python. I assume you used the crontab of the user that can run the command.When you execute a command incronyou must specify the full path to the command. To find the full path tokubectl, you issue the following in Terminal:which kubectlIt will print the full path.Then, you edit your script (assuming the full path is "/opt/Kubernetes/bin"):import os
os.system('/opt/Kubernetes/bin/kubectl get pods --context students-cmn')
|
I have below small python scriptimport os
os.system('kubectl get pods --context students-cmn')when i run this command manually from terminal it is working , no issue , so i configured it to run as a cron job , but when cron job triggered getting below errorsh: kubectl: command not foundwhy , when the cronjob triggered , kubectl not working ?can anyone please help
|
kubectl terminal command not working from crontab , how to fix?
|
You can make the cron expression configurable like this@Scheduled(cron ="${some.trigger}")You can set this value from yourapplication.propertiesfile for dev/prod profiles. In test mode you can set this to whatever value you want using profile specific properties file, for exampleapplication-test.properties
|
Spring Boot allows you to create background "cron-like" tasks like so:@Component
public class MyTask {
// Every hour on the hour
@Scheduled(cron = "0 0 0/1 1/1 * ? *")
public void doSomething() {
// blah whatever
}
}This makes automated integration testing a wee bit difficult! I shouldn't have to have a running integration testing just hanging for an hour, waiting to see what happens when my task runs at the top of the hour. Nor should I have to wait to run my test near the hour so that I can confirm proper behavior at the top of the hour!Is there a way to make thesecronvalues configurable?That way if I want to run my app in "test mode" I could schedule theMyTask#doSomething()method to run, say, every 30 seconds, etc.
|
Making Spring Boot cron tasks configurable
|
+50You should write some script that will test conditions and perform all required operations.if is_work_finished_less_then_month_ago():
return
else:
try:
generate_normal_report()
except some_error as e:
report_about_error(e)Then run it every hour or day.If you afraid of too many error_reports then do the same thing inreport_about_error()method: check last time you sent report and do not send it if it's too often.
|
Our customer wants us to create a report every month.In the past, we used a @monthly cron job for this task.But this is not reliable:The server could be down in this minute. Cron does not re-run those jobsIf the server is up, the database could be unreachable in this moment.If the server is up and DB is up, there could be a third party system which is not reachableThere could be a software bug.What can I do, to be sure that the report gets created monthly?It is a Django based web application
|
@monthly cron job is not reliable
|
This will fix your issue:0 0 * * * /some/path/to/a/file.php >> /tmp/log/cron-`date +\%F`.log 2>&1
|
I'd like to log cron output to a dated file —/tmp/log/cron-2014-12-17.log$ mkdir /tmp/log
$ chmod 777 /tmp/log
$ ls -lah /tmp/log
drwxrwxrwx 2 root root 4.0K Dec 17 21:51 .Cron (viarootuser)* * * * * /usr/bin/php /path/to/script.php > /tmp/log/cron-$(date "+%F").log 2>&1/tmp/logremains empty after each minute.If I run the script manually from command line a log file is created, and output is as expected.// Running it manually as a CLI works fine, but not as a cron
$ /usr/bin/php /path/to/script.php > /tmp/log/cron-$(date "+%F").log 2>&1Also, if I create a file and chmod 777 it, the cronwillwrite output to this created file. It just won't create one on the fly.// Let's create it first
$ touch /tmp/log/cron.log
$ chmod 777 /tmp/log/cron.log
// wait for the next minute...
$ tail -f /tmp/log/cron.log
output... output... output...But this doesn't work for dynamic names like/tmp/log/cron-2014-12-17.log.What am I missing?
|
How can cron output to a new log file based on date?
|
After many trials and research, I discovered that the solution was using theHOME=variable, not thePATH=variable, like so:SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=""
HOME=/var/www/html/cronsAnd then each of the lines would just look like:*/2 * * * * root /usr/bin/php cronfile.php >> logs/cronfile_`date +\%Y\%m\%d`.logHope this helps someone else with the same issue I had in the future.
|
I am attempting to use relative paths in my crontab file on CentOS 6.4, so that I do not have to repeat the same absolute path over and over again. At the top of my crontab file, located here:/etc/crontab, I have:SHELL=/bin/bash
PATH=/var/www/html/crons
MAILTO=""
HOME=/And each of my commands looks like:*/2 * * * * root /usr/bin/php "cronfile.php" >> "logs/cronfile_"`date +\%Y\%m\%d`".log"I'm expecting that it'll run thecronfile.phpPHP file in the/var/www/html/cronsdirectory, and save the output from this to/var/www/html/crons/logs/cronfile.log. However, the file is not being run and the log file is not being created.The command works fine if I run just:/usr/bin/php "cronfile.php" >> "logs/cronfile_"`date +\%Y\%m\%d`".log"from the command line aftercding into the/var/www/html/cronsdirectory.Please advise, thanks.
|
Using Relative Paths in Crontab
|
Here is anice articlefor managing your Cron jobs from PHPhttp://net.tutsplus.com/tutorials/php/managing-cron-jobs-with-php-2/this example contain full description of how to write a Cron job from PHP which is manageable from interface with complete source code.
|
How can i set a cron job programatically ,we made a installer for our project and on the installation time i need to set a cron job programatically with PHP.Please note that the project can be running on LINUX/WINDOWS ,how can i achieve that ? or is there any better option than CRON JOB.I am using Codeigniter(Native php based solutions are always welcome , but it will be very helpful if it is through CI)THE cron job includesCheck a particular table and remove invalid dataInsert values to DB from mailServerChecking the availability of some files.Thanks.
|
Set cron job php
|
We will useFIFO(First In First Out) in a bash script. The script needs to run beforecron(or any script, any terminal that call theFIFO) to sendffmpegcommands to this script :#!/bin/bash
pipe=/tmp/ffmpeg
trap "rm -f $pipe" EXIT
# creating the FIFO
[[ -p $pipe ]] || mkfifo $pipe
while true; do
# can't just use "while read line" if we
# want this script to continue running.
read line < $pipe
# now implementing a bit of security,
# feel free to improve it.
# we ensure that the command is a ffmpeg one.
[[ $line =~ ^ffmpeg ]] && bash <<< "$line"
doneNow (when the script is running), we can send anyffmpegcommands to the named pipe by using the syntax :echo "ffmpeg -version" > /tmp/ffmpegAnd with error checking:if [[ -p /tmp/ffmpeg ]]; then
echo "ffmpeg -version" > /tmp/ffmpeg
else
echo >&2 "ffmpeg FIFO isn't open :/"
fiThey will be queuing automatically.
|
I am trying to encode many videos on my server, but FFMPEG is resource intensive so I would like to setup some form of queueing. The rest of my site is using PHP, but I don't know if I should use PHP, Python, BASH, etc. I was thinking I might need to use CRON but I am not really sure exactly how to tell ffmpeg to start a new task (from the list) after it finishes the one before it.
|
How do I set up an ffmpeg queue?
|
Add this line to your crontab, and make sure the location ofphpis correct (check it out withwhich php).*/15 * * * * /usr/bin/php /var/www/vhosts/sitename/httpdocs/runcron.phpThat's simple ;-)
|
Is it possible to set up a cron job that will execute a php script?I have a php file and i want to run every 15 minutes using cron job.My php file path: www.sitename.com/runcron.phpfull path: /var/www/vhosts/sitename/httpdocs/runcron.phpI using centos server.Thank you
|
Run PHP File from cron job?
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.