Response
stringlengths 8
2k
| Instruction
stringlengths 18
2k
| Prompt
stringlengths 14
160
|
---|---|---|
+25There is a known issue with whenever and rvm integration. I would suggest following the instructions on the whenever gem page:RVM IntegrationSee also:Whenever issues related to rvm
|
I have the followingschedule.rbevery 1.minute do
runner "User.persist_things"
endBut looking at mylog/cron.logfile, the output is the following:/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require': no such file to load -- bundler/setup (LoadError)
from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems/custom_require.rb:31:in `require'
from /Users/felipeclopes/projects/example/config/boot.rb:6
from script/rails:5:in `require'
from script/rails:5I am using RVM with ruby, the current version is:$ ruby --version
ruby 1.9.3p392 (2013-02-22 revision 39386) [x86_64-darwin10.8.0]So it seems that the cron job is loading the incorrect ruby version, but I don't know how to fix this. Can you help me figuring out?
|
Error in bundle when executing cron.job with Whenever
|
To make it upgrade safe just add this to your config_overrite.php$sugar_config['cron']['min_cron_interval'] = 0;
|
I need some help setting up my crontab for SugarCRM.My SugarCRM log just looks like this:Wed Aug 21 10:36:02 2013 [5145][1][FATAL] Job runs too frequently, throttled to protect the system.
Wed Aug 21 10:37:01 2013 [5156][1][FATAL] Job runs too frequently, throttled to protect the system.
Wed Aug 21 10:38:02 2013 [5181][1][FATAL] Job runs too frequently, throttled to protect the system.
Wed Aug 21 10:39:02 2013 [5196][1][FATAL] Job runs too frequently, throttled to protect the system.I run crontab -e and this is what I have in it:* * * * * cd /var/www/sugarcrm; php -f cron.php > /dev/null 2>&1I have my "Run Mass Email Campaigns" job running once an hour. My campaign emails aren't being sent. I can send them if I go into the Email Queue and click the Send Queued Campaign Email button, but even then it only sends out about 500. I have about 50,000 to send out lol. Any help with the crontab is greatly appreciated.
|
Setting up Crontab in SugarCRM
|
This is because you are redirecting the output ofechotomailso there is nothing to write to the log file. As a result, the log file is empty.If you want to write the output ofechoto the log file and also send it tomail, useteeas shown below:echo 'blabla' 2>&1 | tee /test/test.log | mail -s "Cron report"[email protected]
|
I have a cronjob:* * * * * root echo 'blabla'It is an easy one :)Now, I would like to send an email when this cronjob is done, but also to store the log in a log file.I tryed this:* * * * * root echo 'blabla' | mail -s "Cron report"[email protected]> /test/test.log 2>&1The email is sent and the test.log file is created, but the test.log file is empty.Any idea why?
|
How to send email and store log file from a single cronjob?
|
You need acron job(not sure if Yii has functionality to make this easier).PHPBasically you need to write a PHP script that re-counts the votes, and puts them in a separate table, and you need that script to run every hour or, how often you want it.The cron command would be something like:php updateRatings.phpMySQLYou can use a command similar to the next one as a cron.mysql -h HOST -u USER -pPASS -e "UPDATE ..."For the actual SQL query - you should check this question:MySQL - UPDATE query based on SELECT QueryUPDATE:You could use a query similar to this:UPDATE
tbl_averages ta
SET
rating =
(SELECT
AVG(tr.rating)
FROM
tbl_rating tr
WHERE
ta.shop_id = tr.shop_id)With the table tbl_averages containing the colsshop_idandrating.
|
I am working on a website, which has 10 star rating system. All ratings are stored in tbl_rating and have attributes:id
heading
description
rating (number of stars, 1 to 10)
shop_id (each rating belongs to a shop - my site is a catalog of shops)My question is, how is it the best way to count average rating for a shop (basicaly I only need to sum all ratings with particular shop_id and divide them by number of those ratings). Every shop has also column avg_rating, where I can store the value.Is there any way to tell MySql database to count this statistics every hour? Should I count it after every new submitted rating or even every time the shop attribute avg_rating is queried? Is there any way to tell the database to do this automatically or do I have to run these actions from PHP? I am using PHP, Yii framework and MySQL database.Thanks for any help.
|
Average rating value counting
|
I'm afraid launchd(8) does not support mailing of stdout/stderr out of the box. Here's a workaround:Redirect output viaStandardOutPathandStandardErrorPathto files in a dedicated directory. Then setup a job which mails every file in this directory. Trigger this job with theQueueDirectorieskey. Make sure this script removes the files after mailing them.
|
Migrating from an old mac to a new one.Trying to migrate the user crontab I had on the old mac.Now I know I can probably get cron to run by creating /etc/crontab - but given that apple has deprecated it in favour of launchd - I thought I'd take a swing at migrating my crontab to launchd plist files. Always fun to learn something new :)The crontab isn't that hard - I tend to set up shell scripts that do the work and then just call them at scheduled times.I can call these fine from the plist at the same times - no issues.But - at the top of my crontab I had MAILTO=my-gmail-email-address - so that instead of sending mail to the local user on the box's mail spool it sent them to gmail for me.I can't see that you can configure this for a launchd plist file.So - before I go modify all my scripts to redirect all output to tmp files then mail the tmp file (would have to do this in quite a few scripts) - is there a way to do this at the launchd level?
|
Converting cron to launchd - MAILTO
|
You open a shell (probably through SSH) to your serverYou run the commandcrontab -eYou edit the crontab according to your needs (if you want to run a php script over http you need to usewget)You save and exit If you didn't make any mistakes, you will get a message that crontab was updated
|
I am currently reading this documentationherewhere I want to use CRON. Now it says in the first section that I need to enter in a command:crontab -e.Do I only need to enter this in a simple text editor file and just upload the file into the server?I am using helios.hud.ac.uk so would this be the correct command:* * 25 10 * helios.hud.ac.uk/u00000000/Mobile/inactivatesession.phpThis will execute this php script below (inactivatesession.php):<?php
include('connect.php');
$createDate = mktime(0,0,0,10,25,date("Y"));
$selectedDate = date('d-m-Y', ($createDate));
$sql = "UPDATE Session SET Active = ? WHERE DATE_FORMAT(SessionDate,'%Y-%m-%d' ) <= ?";
$update = $mysqli->prepare($sql);
$update->bind_param("is", 0, $selectedDate);
$update->execute();
?>The url for this php script is: helios.hud.ac.uk/u00000000/Mobile/inactivatesession.phpI havn't used CRON before so just need little help on it.Thanks
|
How to run crontab-e?
|
I would write a simple launcher script that does the following:Takes two command line options:--startSet up the classpath and environment like JAVA_HOME for the jar to run.Spawnjava -jar myJar.jar.Capture the process ID and store it in themyJar.pidfile in a specific location.--stopRead the process ID frommyJar.pidand send akillsignal.Then schedule two jobs incron, one to call this launcher script with--startargument, at 9AM, and the other to call the same script with--stopargument, at 5PM.I would also have ashutdown hookregistered in my application to gracefully exit when the kill signal is issued.
|
I have compiled my JAVA code into a jar file which I have ported to my ubuntu server. I can start it manually the usual way usingjava -jar myJar.jarbut I'd like my program to be active only for 8 hours. How can I go about setting my jar file up as a process which starts at 9AM and also which automatically closes at 5PM?
|
How to set up a cron job to start and stop a java jar?
|
In cron the%(percent) sign needs to be escaped. You should comment out the percent signs with a\(backslash) in front of them. i.e.,date +\%Y-\%m-\%d-\%H-\%M
|
I know this seems pretty trivial but I can't see to get this to work in cronjob.I am runningzip -r /backup/$(date +'%Y%m%d').zip /var/wwwThis works fine. It gives me zip file in my backup directory.But I will open Cron tab withcrontab -eAnd I append this to the bottom of the file so it does daily updates.This is where it doesn't work.What am I doing wrong?Edit: crontab looks like0 1 * * * /home/serveradmin/backup.sh
|
Simple Cronjob to backup a directory
|
Here are some of my tries :)The following worked fine in my case:wget -O /dev/null http://example.com/cron/my-cron.php >/dev/nullAlso the following worked fine (I think this is better if we have 'https://' in the URL):/usr/bin/php -q /home/user/public_html/cron/my-cron.php >/dev/nullAnother one:curl -s http://example.com/cron/my-cron.php >/dev/null 2>&1If you do not wish to receive an email notifying you of a specific cron job, add the following line to the command:>/dev/null 2>&1Ref:http://docs.cpanel.net/twiki/bin/view/AllDocumentation/CpanelDocs/CronJobs
|
I am using X10 hostingServer ishttps://boru.x10hosting.comIn add cron job i had givenCommand/usr/bin/php -q /home/mohanphp/www/quote_bot/sms_cron.php >>/home/mohanphp/www/quote_bot/log/cron_log.txt 2>&1I had tried/usr/bin/php -q /home/mohanphp/www/quote_bot/sms_cron.php >/dev/null 2>&1
/usr/bin/php -f /home/mohanphp/www/quote_bot/sms_cron.php >/dev/null 2>&1I had set cron for every 5 minutes.Please help me what wrong i did with the command.
|
How to set cron job in cpanel
|
You're running the command in the background (&at the end). This means that the shell that cron has started to run the command will not wait for its completion and terminate as soon as the command has been started. If your program now tries to write tostderr, nothing is connected to the read end and you get a SIGPIPE. If you redirect to a file, this doesn't happen because the running process knows where to write to.The other way of fixing this would be to run the command in the foreground, i.e. without the&at the end. This is better practice anyway.
|
I write a program, which can output tostderr. When I run it by Linuxcrontab, I must redirect thestderr. if not, the program will exit with aSIGPIPE. Why?NOT OK45 10 * * * /home/sandy/test > /home/sandy/test.log &OK45 10 * * * /home/sandy/test > /home/sandy/test.log 2>&1 &
|
In Linux crontab, stderr of my program must be redirected, why?
|
From crontab manpage:Percent-signs (%) in the command, unless escaped with backslash
(\), will be changed into newline characters, and all data after the
first % will be sent to the command as standard input.
|
I have the following command in my cron file:*/15 * * * * NODE_ENV=production ~/bin/node ~/myapp/app.js > /var/log/nodelog/nodelog_`date "+%Y-%m-%d_%H-%M"`.logThe command itself runs OK when copied and pasted into the bash shell, but the cron job keeps sending the following error message:/bin/sh: -c: line 0: unexpected EOF while looking for matching ``'
/bin/sh: -c: line 1: syntax error: unexpected end of fileWhy does it run OK from the command line, but fail in the cron job? Is there a difference between the syntax expected on the command line and that expected in cron?
|
Command runs from command line, not from cron?
|
./etc/cron.daily/maj_cat is a relative path, and var/www/dev/update.php too, try:00 16 * * * /etc/cron.daily/maj_catand maj_cat:php /var/www/dev/update.phpTo you can do:00 16 * * * /usr/bin/env php /var/www/dev/update.php
|
I want to update some stuff in my database everyday at 16:00.So I use crontab which execute command which run my file.php which run the update. It works perfectly when I execute the command in the bash but There is a problem with the crontab.crontab:00 16 * * * ./etc/cron.daily/maj_catmaj_catphp var/www/dev/update.phpThanks!
|
Can't execute command from crontab?
|
Cron is a time-based job scheduler in Unix-like computer operating systems. Which means you can not configure it on Windows.
|
it's a one line question and i don't know how to describe itmysystem config:-
os: windows Xp
server : Wamp server (latest)is this posible ?
|
can i configure cron job for localhost
|
To my knowledge, you can't use Spring'sCronTriggerto start only from a certain date.Cron syntax doesn't support running something daily from an arbitrary date; it supportsEITHERrunning something dailyORrunning once on an arbitrary date — but not both at once. That means you could use two triggers: have one cron trigger set to trigger on your start date; then create a new daily trigger when that first trigger occurs.However this only works properly with if the cron trigger you are using supports years, for example Quartz has an option year field in its cron trigger. Spring'sCronTriggerdoesn't support years. So if you did try to schedule something for a specific date (say0 0 12 26 1 ?for noon on Australia day) then it would run every year, not just once, causing duplicate triggers to be created each year.Instead I recommend creating a simple trigger to run daily, ie:Trigger trigger = new CronTrigger("0 0 12 * * ?);So your code will run daily. Then add a simple date check in your code: if you haven't reached the start date then skip your task, ie:if ((new Date()).after(startDate)) {
// Run your task here
}
|
I am using springs task scheduler(ConcurrentTaskScheduler) to schedule my tasks.
I am using the APIpublic ScheduledFuture schedule(Runnable task,Trigger trigger)to execute my tasks.The trigger I am using is the CronTrigger.I am initializing the trigger using the following statementTrigger trigger = new CronTrigger(cronExp);I need to write a cronExp in such a way that it starts at a specific date and executes daily from then on.I checked out the API for ConcurrentTaskScheduler but I could find appropriate API to achieve/I might have missed some API.Can anyone suggest me a way to achieve the above requirement?
|
Writing a cron Expression in springs
|
I'm not that deep into cron jobs, but I know a bit about pynotify. It uses libnotify and some DBUS stuff, so somewhere it makes the call to the DBUS and iirc it also passes the display id on which the notification should be shown.Now, by default cron's don't work with GUI applications, you have to specify a display for them to use:00 * * * * myname env DISPLAY=:0 python ~/scripts/script.pyThis will make the cron use the current display (Desktop).If you're running on Ubuntu this page might be of interest for you:https://help.ubuntu.com/community/CronHowto
|
I've written a script that uses pynotify to give an alert. it works just fine when I run it (python script.py), but when run from cron with00 * * * * myname python ~/scripts/script.py, it doesn't work! I haven't a clue why. Here's the snippet:if os.path.isfile(os.path.expanduser('~/.thumbnails/normal')+'/'+thumbnail):
n = pynotify.Notification(video_file[0], 'finished download', os.path.expanduser('~/.thumbnails')+'/'+thumbnail)
else:
n = pynotify.Notification(video_file[0], 'finished download', '/usr/share/icons/gnome/48x48/mimetypes/gnome-mime-application-x-shockwave-flash.png')
print n
n.show()directing the output to ~/log.file gives:<pynotify.Notification object at 0x16d4e60 (NotifyNotification at 0x13804e0)>and no errors, so i'm not quite sure where else to look.
|
PyNotify not working from cron?
|
Add this to your crontab to get Drush to update your Drupal copy everyday at 12:01 PM:1 12 * * * drush -y up
|
I am trying to keep a couple of Drupal sites updated and I tired of the whole process. I recently find out about Drush and I was wondering if there is a module or a CRON command I can setup to keep the sites updated for me.Thank you.
|
Keep Drupal updated
|
Quartz definitely support cron-like syntax (with theCronTrigger) but your requirements are not clear. Also maybe have a look atJcrontaborcron4j.As a side note, the ability to declaratively create cron-like schedules to trigger EJB methods is one of the most important enhancement of the Timer Service in EJB 3.1 (using the@Scheduleannotation). Below, an example taken fromNew Features in EJB 3.1:@Stateless
public class NewsLetterGeneratorBean implements NewsLetterGenerator {
@Schedule(second="0", minute="0", hour="0",
dayOfMonth="1", month="*", year="*")
public void generateMonthlyNewsLetter() {
... Code to generate the monthly news letter goes here...
}
}
|
Timer Tasks in Java EE are not very comfortable. Is there any util, to configure timer with cron syntax like "0 20 20 * * "?I wonder, if it would be a good way to use Quartzinside (clustered) Java EE application. According tohttp://www.prozesse-und-systeme.de/serverClustering.html(german page) there limits with Quartz and Java EE clustering:JDBC must be used as job store for QuartzOnly cluster associated Quartz instances are allowed to use this JDBC job storeAll cluster nodes must be synchronized to the split secondAll cluster nodes must use the same quartz.properties fileI would prefer an easier way for configuration of timer service, instead an not Java EE managed scheduler.
|
Cron syntax with Java EE 5?
|
Everything seems to be working now, the solution was to move mymain.ymlfile into.github/workflows. I also movedmy_file.pyfrom alternate branch into the master branch.Onehelpful commentrecommended specifying the ref branch where you runmy_file.pyifmy_file.pyis not located in the default branch.
|
I assume it's possible to schedule a python script to run every day for example, from my github repository.After searching, I've come up with the following main.yml file that resides in the master branch of the repo:the .py file I want to run resides in another branch; I suppose it doesn't have to if it causes an issue, but the script isn't running either way.I'm new to a lot of this, and have a funny feeling I'm missing fundamental pieces to get this working.name: py
on:
schedule:
- cron: "30 11 * * *" #runs at 11:30 UTC everyday
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: checkout repo content
uses: actions/checkout@v2 # checkout the repository content to github runner.
- name: setup python
uses: actions/setup-python@v2
with:
python-version: 3.8 #install the python needed
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install flake8 pytest
if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
ref: # branch
my_other_branch
- name: execute py script # run file
run: |
python my_file.py
|
How do I simply run a python script from github repo with actions
|
+100Better of doing it with a mail package in your os as following.it will also pipe any error output of your mongo_backup script to email as message and email subject will be current date-time.00 05 * * * /bin/bash /home/ubuntu/mongo_backup.sh 2>&1 | mail -s $(date "+%Y%m%d-%H%M%S")[email protected]
|
I have my crontab configured as[email protected]#1am every day (EST)
00 05 * * * /bin/bash /home/ubuntu/mongo_backup.shwhich sends me email with the subjectCron <ubuntu@ip-XXX-XX-XX-XX> /bin/bash /home/ubuntu/mongo_backup.shBut I need with some custom date<Date> MyProjectName
|
How to change the subject when sending email using crontab?
|
crondis now running asmyuserafter following the answer below.https://github.com/gliderlabs/docker-alpine/issues/381#issuecomment-621946699DockerfileFROM alpine:latest
USER root
RUN apk update \
&& apk upgrade \
&& apk --no-cache add dcron libcap
RUN groupadd -r -g 2001 myuser \
&& useradd -r -u 1001 -g myuser myuser
RUN mkdir /home/myuser \
&& chown myuser /home/myuser
RUN chown myuser:myuser /usr/sbin/crond \
&& setcap cap_setgid=ep /usr/sbin/crond
COPY --chown=myuser:myuser cronjob /home/myuser/cronjob
RUN crontab /home/myuser/cronjob
COPY --chown=myuser:myuser entrypoint.sh /home/myuser/entrypoint.sh
USER myuser
WORKDIR /home/myuser
ENTRYPOINT["./entrypoint.sh"]entrypoint.sh#!/bin/sh
# Start cron daemon.
crond -b -l 8
# Start application.
|
I am trying to run a container with the following scripts:DockerfileFROM alpine:latest
USER root
RUN apk update \
&& apk upgrade \
&& apk --no-cache add busybox-suid su-exec
RUN chmod u+s /sbin/su-exec
RUN groupadd -r -g 2001 myuser \
&& useradd -r -u 1001 -g myuser myuser
RUN mkdir /home/myuser \
&& chown myuser /home/myuser
COPY --chown=myuser:myuser entrypoint.sh /home/myuser/entrypoint.sh
COPY --chown=myuser:myuser cronjob /home/myuser/cronjob
USER myuser
RUN crontab /home/myuser/cronjob
WORKDIR /home/myuser
ENTRYPOINT["./entrypoint.sh"]entrypoint.sh#!/bin/sh
# Start cron daemon.
su-exec root crond -f -l 8
# Start application.I have read that elevating privileges is not good practice. Therefore, I wish to eliminate usage ofsu-exec+chmod u+s /sbin/su-execin my script. I triedsuandsudoas well but they were asking forrootpassword so I switched tosu-execinstead. I needed to elevate privilege becausecronddoes not run properly without starting it asroot. This container will be run in Kubernetes.Is there a better way to do this?
|
How To Run Cron As Non Root In Alpine
|
Try to change.timeZone('utc')(per the docs) to.timeZone('Etc/UTC')(also per the self-contradictory docs).
|
I have written a scheduled function in node.js using typescript that successfully deploys.The related pub/sub topic gets created automatically but somehow the related scheduler job does not.This is even after getting these linesi scheduler: ensuring necessary APIs are enabled...
i pubsub: ensuring necessary APIs are enabled...
+ scheduler: all necessary APIs are enabled
+ pubsub: all necessary APIs are enabled
+ functions: created scheduler job firebase-schedule-myFunction-us-central1
+ functions[myFunction(us-central1)]: Successful create operation.
+ Deploy complete!I have cloned the sample athttps://github.com/firebase/functions-samples/tree/master/delete-unused-accounts-cronwhich deploys and automatically creates both the related pub/sub topic and scheduler job.What could i be missing?
|
Related Scheduler Job not created-Firebase Scheduled Function
|
So for anyone coming across this, I had to come back to this for a permanent solution today - as Daylight savings is about to change! The root issue here is that wp_schedule_event - accepts a parameter thats a number of seconds until the next run. That parameter is saved to the cron array - and it really doesn't care what timezone you're in. It just keeps running at that interval. In order to fix this - I had to switch to wp_schedule_single_event.It seems counter-intuitive, because we want this to run on an interval. But the difference is - we NEED to recalculate the next timestamp to run at:if ( ! wp_next_scheduled( 'my_check_cron_event' ) ) {
wp_schedule_single_event( strtotime('tomorrow America/New_York'), 'my_check_cron_event' );
}The difference here is strtotime() will get the correct timestamp each DAY - accounting for daylight savings, rather than simply running every 24 hours. Hope that helps someone!
|
So I ran into an issue on a website this morning that uses WP Cron. The code looks like this://Schedule the cron to run if not scheduled
if ( ! wp_next_scheduled( 'my_check_cron_event' ) ) {
wp_schedule_event( strtotime('tomorrow America/New_York') , 'daily', 'my_check_cron_event' );
}The issue is pretty simple. That code works fine, essentially I want to run the function at midnight local time, every day. So when I first run the function - it gets the timestamp for midnight tomorrow - local time. And ever since - the functino has been running.Now this weekend - because of daylight savings time, the function doesn't actually ever get RESCHEDULED - its just set to run every 24 hours. So the function started running at 11pm. Of course that's easy to fix - but will just break again. I can't really find any good posts on the topic - how would you deal with:wp_schedule_event running daily when daylight savings time changes?Just to preempt an obvious answers here: I can't run a proper cron - it needs to be done through wp. Our host simply doesn't support it, it sucks - but that's the client. Any advice would be greatly appreciated!
|
wp_schedule_event and Daylight Savings
|
Using thetask scheduleris the correct way to go about this. If you have a large number of reminders to process then setting them up to execute asqueued jobsis the recommended approach. That way the load on the server is minimized and does't bottleneck the system for user traffic.You'll probably want to create aconsole commandto handle the processing logic and create the jobs.Chunkingthe jobs will also be helpful, as that will stagger out the number of jobs processed in a given batch.
|
Suppose I have a database like this.| task | time |
|---------------------------|---------------------------|
| Remind me to water plants | 2018-02-18T19:32:10.486Z |
| English Test | 2018-10-8T09:30:00.000Z |
| Math Test | 2018-10-8T10:30:00.000Z |And I want to send a reminder notification to the user at the time it has been requested (or maybe an hour before) by the user and also execute some other block of code at that specific time when reminder notification is triggered.I am thinking of writing a cron job something like this* * * * * php /laravel-project/artisan schedule:run >> /dev/null 2>&1as mentioned in laravel documentation (https://laravel.com/docs/5.6/scheduling).And inside that script, I will be looping onto current time reminders and reminders within next hour and perform actions.Is it a good practice? Won't it increase traffic between PHP and database? What if i have lot of reminders within the same hour, looping into that and executing blocks of code foreach reminder will be it a good idea?Please suggest ideas
|
Is cron the best way of writing reminder based application in php?
|
What about this one.$schedule->command('report:sendEmail')->timezone('America/New_York')->cron('30 21 * * 1,3');Above is the command to run your job at every Monday and Wednesday at 9:30 PM.Below is the format of cron job# Use the hash sign to prefix a comment
# +---------------- minute (0 - 59)
# | +------------- hour (0 - 23)
# | | +---------- day of month (1 - 31)
# | | | +------- month (1 - 12)
# | | | | +---- day of week (0 - 7) (Sunday=0 or 7)
# | | | | |
# * * * * * command to be executed
#--------------------------------------------------------------------------I suggest you to usehttp://corntab.com/for creating cron rules in future.:)
|
How to schedule the job which needs to be run on custom days in Laravel.eg) Monday and Wednesday only.Wondering will it work or not?$schedule->command('report:sendEmail')->timezone('America/New_York')->weekdays()->mondays()->wednesdays()->dailyAt('21:30');
|
How to set up Laravel schedule job on Monday and Wednesday
|
From the point of view of cron it doesn't matter if the functions are synchronous or asynchronous. Cron doesn't run your individual functions - it starts the processes and waits for them to finish. How the process works internally is irrelevant.Now, what you need to take into account if the process can potentially run for longer than the interval between executions is that it is possible that two processes will run at the same time - unless you explicitly do some locking to prevent that.If you want your processes to potentially run at the same time (if the new process will not wait for the previous one to finish) then you will have to handle concurrency with possible race conditions. This may not be trivial but you will still have to deal with that even if you used a synchronous, blocking or multithreaded environment so this is not Node-specific or async-specific.
|
Is it a good idea to run node async functions in cron jobs?Yes, NodeJS is single threaded. What will happen when cron invokes function() multiple times?Say the situations is:
- CRON Job runs 5 mins calling function()
- The function() may take more than 5 minutes to run
- The function() is asyncI need to a Backend application in NodeJS that does:
- Read data from MongoDB (once)
- Based on the data, there might be many Third Party API calls, say GOOGLE API to calculate driving distance between two points
- Save the total distance data back to the MongoDB
- Update Redis cacheHow would you do it?Your comments are much appreciated!!Thank you.
|
Is it a good idea to run NodeJS async functions in CRON Jobs?
|
Please add the PHP command to be executed. It should be like this.* * * * * /usr/local/bin/php /home/mahsanwe/cron_backups.phpYou can also refer the below article for more understanding.https://manage.accuwebhosting.com/knowledgebase/3043/How-to-set-the-cron-job-to-run-a-PHP-script-in-cPanel.html
|
I set up a cron job in Cpanel according to backup but received this email alert:
/usr/local/cpanel/bin/jailshell: /home/mahsanwe/cron_backups.php: Permission deniedHow to fix it?
|
Permission denied cron job in Cpanel
|
I'm using a little bit different code, but the end result is what you were trying to achieve: getnotify-sendto work from a python script viacrontab.Here's my Python 3.x script:import subprocess
subprocess.Popen(['notify-send', 'Running.'])And here's how I setupcrontab:DISPLAY=:0.0
XAUTHORITY=/home/matrix/.Xauthority
*/1 * * * * /usr/bin/python3 /home/user/path/to/my/script.pyThis should work with Ubuntu 16.04 and python3, I cannot speak for other OS's, but you can give it a try. Usewhichto check the path of yourpythonorpython3installation.By the time I finished this answer the "Running." notification popped up at least 3 times.
|
This is my python script for notify send:#! /usr/bin/env python
import os
mstr='The scoreis 102/3'
title="SCORE"
os.environ.setdefault('DISPLAY', ':0.0')
os.system('notify-send -i "notification-message-IM" "'+title+'" "'+mstr+'"')It works normally when I run the script,but while trying to run it from cron it is not workingI have tried reference from this links:Cron scheduler of python script using notify-sendCron with notify-sendEven in crontab i have tried to run a notify-send command like this:* * * * * export DISPLAY=:0.0 && /usr/bin/notify-send "How are you"But of no help.Is there anything I am doing wrong please suggest.
|
Crontab of python script using notify-send
|
You can use BackgroundJob.Schedule(Expression> methodCall, DateTimeOffsetdt) method.BackgroundJob.Schedule(methodCall, enqueueAt);
|
Hangfire.io supports making a CRON-like scheduling of recurring jobs. But how do I specify, that a specific job should be run once, at a specific date/time, e.g. that a job should be run June 4th 2016, at 16:22 - and only at that specific point in time?A similar way to ask the same question could be: how large a subset of the CRON expression describedhere, is supported by Hangfire? (The described CRON expression supports a "Year"-field which could be used).Also, do you think Hangfire is the best choice to schedule one-off batch jobs in the first place, provided that I use Hangfire for job processing?
|
How do I schedule a job to be run at a specific date in Hangfire
|
To do this I used curl inside dailyProc.shtoday=`date +"%d%m%y"`
year=`date +"%y"`
dm=`date +"%m%d"`
`tar -zxf /path/to/input/$today.tgz -C /path/to/output`
echo "starting data proc"
`/usr/bin/curl "myserver.com/dataproc.php?date=$dm?year=$year"`
echo "data proc done"
|
I am trying to run a php file every night at a certain time using crontab, however the php needs to be running as a www-data because of the directory permissions. To run it aswww-dataI am using therootcrontab and changing the user in there, like so:* 20 * * * sudo -u www-data /usr/bin/env TERM=xterm /path/to/dailyProc.shdailyProc is as followstoday=`date +"%d%m%y"`
year=`date +"%y"`
dm=`date +"%m%d"`
`tar -zxf /path/to/input/$today.tgz -C /path/to/output`
echo "starting data proc"
`/usr/bin/php5 -f /path/to/dataproc.php date=$dm year=$year`
echo "data proc done"All other commands in dailyProc.sh work but the php doesnt run. The php is using an output buffer and writing it to a file, which works fine calling it from the command line but doesnt work when calling by cron.I can also definitely run dailyProc.sh from the command line aswww-datausingsudo -u www-data dailyProc.shand everything works as expected.Is there any reason I would not be able to run this php file indailyProc.shusing crontab when everything else in it works?
|
Execute php file from bash script as www-data using crontab
|
I had the same problem.
The issue is because I was running the Rscript as root, but Rscript should be run as souza, current user.
To fix that, I edited the crontab for user souza "sudo crontab -u souza -e" and the Rscript is run as souza and not as root.
Now it is working
|
I want to try how to render html from R markdown file but from a bash script running as Cron jobs. I don't know why everything works fine, except running as Cron jobs. What I do:My script is a demo script from Rstudio---
title: "test"
author: "sms"
date: "24 maja 2015"
output: html_document
---
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.
When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
```{r}
summary(cars)
```
etc.This script works without any problem in Rstudio.Next I try to run an Rmd script from terminal:Rscript -e "require( 'rmarkdown' ); render('/home/sms/Dokumenty/R/test.Rmd', 'html_document')"There wasn't any problem. It works.So I create bash script#!/bin/bashRscript -e "require('rmarkdown'); render('/home/sms/Dokumenty/R/test.Rmd', 'html_document')"and changed chmod 755 test.shAlso works like a charme.But when put in Cron file (admin and user):28 18 * * * sh /home/sms/Dokumenty/R/test.shIt doesn't worksAny idea what am I doing wrong?
|
Running bash script as Cron job with R Markdown
|
You are correct, you cannot setup programmatically the cron configuration.You can configure a single cron which triggers a customized functions. This functions can read the configured crons (like datastore entities) and the launch different task based on your needs
|
I am writing a wrapper around the Github Issues API to allow managers in my company to set up daily reminder emails to be sent to their devs. I want this to be configurable through an admin console, and give them the flexibility of setting up reminders at any time of day and any number of times a day.The main App Engine cron system is configured statically through the cron.yaml file and cannot be changed by user action. Looking at the documentation it appears like I can only do this by reimplementing an entire cron infrastructure on top of the basic App Engine cron. Am I missing something? Is there anything like this that is already available elsewhere?
|
Programmatically modify cron schedule in Google App Engine
|
Just need to check if the IP trying to access the file is the server, otherwise stop it.if($_SERVER['REMOTE_ADDR'] !== '127.0.0.1'){
die('no access');
}
|
I have a file called backup.php that creates a backup .sql file of my db and saves it to my folder "backups"I have set up my backups folders file permission to: 700. So now, the backup files files cannot be accessed by a web browser, and I have to get them via ftp. Which is good.I also tried setting my backup.php to the file permission: 700, but I can still run the script by going to the page.So, my question is, how can I restrict people from running my script and only allow a cron job from my server to run the script?
|
Make a specific file only accessible to the server
|
I was able to solve my problem with the following (namespace including restart included for brevity):namespace :deploy do
desc 'Restart application'
task :restart do
on roles(:app), in: :sequence, wait: 5 do
# Passenger restart mechanism
execute :mkdir, '-p', "#{ release_path }/tmp"
execute :touch, current_path.join('tmp/restart.txt')
end
end
after :publishing, :restart
after :restart, :x_bin_rails do
on roles(:web), in: :groups, limit: 3, wait: 10 do
within release_path do
execute :chmod, "u+x bin/rails"
end
end
end
end
|
I have a production environment configured that deploys and works as it should. Although I have encountered an ancillary problem that I can't figure out.I am running the Whenever gem to execute a couple of cron jobs, the Whenever gem capistrano implementation has them deploying correctly and the scripts are executing. Although inside whenever.log I receive the following output:/bin/bash: bin/rails: Permission deniedThe script is using a runner to update from a RSS feed, this has worked without incident on a previous production deployment, although I deployed to the new server using Capistrano.I searched around and found thisquestion, although each time I deploy, I have to make bin/rails executable (due to datestamp deployment from Capistrano). Is there a way to make Capistrano make the file executable for me at deploy? Or is there some inherent security risk with making bin/rails executable?
|
Capistrano + Whenever gems - bin/rails: Permission denied
|
Yes, you can.The easiest way is to merge both commands into single one-liner:mongoexport --db mydb --collection mycollection\ --query "`./test2.sh`" --out ./test2.json && mongo mydb /home/dev/removeDocs.jsBut I would recommend you to create shell script to archive your database:#!/bin/bash
set -e # stop on first exception
mongoexport --db mydb --collection mycollection\ --query "`./test2.sh`" --out ./test2.json
mongo mydb /home/dev/removeDocs.jsIf you want to append each new chunk of exported data, you should replace--outwith standardunixstdioredirection:mongoexport --db mydb --collection mycollection\ --query "`./test2.sh`" >> ./test2.json
|
I would like to run a unix cron every day that does:export all docs that are over 3 month old to a documentremove from the same docs from the collections.For the export part I use:mongoexport --db mydb --collection mycollection\ --query "`./test2.sh`" --out ./test2.jsonand the "./test2.sh" file contains:#!/bin/bash
d=`date --date="-3 month" -u +"%Y-%m-%dT%H:%M:%SZ"`
echo '{ "timeCreated": { "$lte": { "$date": "'$d'" } } }'For the remove part I can do:mongo mydb /home/dev/removeDocs.jsremoveDocs.js:var d = new Date();
d.setMonth(d.getMonth()-3);
db.GameHistory.remove({ timeCreated: { $lte: d} });How can I synchronize the 2 commands? I want to run the remove commend after the export finished. can I merge the 2 to the same cron?
|
mongodb export and remove docs
|
Try calling the command using absolute path, as you call it without shell and under another user account, some commands are not available without specifying absolute path.First find, where is the command located:$ which service
/usr/sbin/serviceThen change your code to:def restart_service(name):
command = ['/usr/sbin/service', name, 'restart'];
#shell=FALSE for sudo to work.
subprocess.call(command, shell=False)
|
I have a small python code that restarts nginx on it's not existing.
When I runsudo python monitor_server.pyall is fine.
When I tried to cron it with root cron (sudo crontab -e) with the line:* * * * * python /root/monitor_server.py > /var/log/my_monitor/cron_log.log 2>&1I get:Traceback (most recent call last):
File "/root/monitor_server.py", line 19, in <module>
restart_service('mongod')
File "/root/monitor_server.py", line 10, in restart_service
subprocess.call(command, shell=False)
File "/usr/lib64/python2.6/subprocess.py", line 478, in call
p = Popen(*popenargs, **kwargs)
File "/usr/lib64/python2.6/subprocess.py", line 642, in __init__
errread, errwrite)
File "/usr/lib64/python2.6/subprocess.py", line 1234, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directoryThe code:def restart_service(name):
command = ['service', name, 'restart'];
#shell=FALSE for sudo to work.
subprocess.call(command, shell=False)
if __name__ == '__main__':
try:
f = urllib2.urlopen("<healthcheck URL>")
except (urllib2.HTTPError, urllib2.URLError) as e:
logging.log(logging.ERROR, 'restarting server')
restart_service('nginx')
|
crontab python subprocess and service restart
|
I was having this same issue where I using the following crontab:0 23 * * * sudo -u myname /home/myname/bin/buildme.sh -f >> /home/myname/log.txtAnd inside the bash script I was using this to get the -f option:while getopts ":f" opt; do
case $opt in
f)
force_full=1
;;
\?)
echo "Invalid option: -$OPTARG" >&2
;;
esac
doneSo I noticed that the option wasn't being honored when I ran this through cron for some reason. Well, adding /bin/bash to the cronjob fixed it right up. The new crontab is:0 23 * * * sudo -u myname /bin/bash /home/myname/bin/buildme.sh -f >> /home/myname/log.txtHope it helps!
|
I know this may have been answered earlier in various posts, but I've not been able to make this run myself.I have a bash script(service.sh)that I would like to run every minute. It needs an argument to be passed (startin this case).Using another script(test.sh)I am scheduling the cron expression for the above script:echo "* * * * * /opt/service.sh start" > /opt/cronForSecops
crontab /opt/cronForSecopsI can see by usingcrontab -lthat this is being set correctly as:* * * * * /opt/service.sh startHowever, theservice.shdoes not run, and I see no logs/files being created (which theservice.shfile is supposed to do, when I run it normally).Can anybody please guide me on where I am going wrong?
|
Run a script with arguments using crontab
|
FromWikipedia:PLS is a computer file format that stores multimedia playlists...You need to use the-playlistswitch, like so:$ mplayer -playlist http://example.com/exampleStream.pls
|
I've built a system using a Rasberry Pi and a piFace. Push buttons are used to naviagate a menu system and select various options. These include playing (using mplayer) locally stored mp3 and m4a files and streaming audio from remote sites in mp3 and pls format.When I manually run the programme on a local terminal - all works well and all these types of media play correctly.However if I run the programme after reboot using the following crontab entry@reboot /home/pi/go.sh >> /home/pi/log.txt 2>&1The programme runs and plays all the media types listed EXCEPT the pls radio streams (e.g. as used by the BBC). With pls input mplayer runs (as shown by ps or top) but no sound emerges.I've tried runing as both pi and root - with the same results.Any suggestions welcome.Kirbylocally stored audio files:mplayer -quiet /home/pi/music/Rehab.m4a* WORKS *mplayer -quiet /home/pi/music/Angel.mp3* WORKS *locally stored audio playlists:mplayer -quiet -loop 0 -playlist /home/pi/tree/playlist_bob_dylan.txt* WORKS *streamed radio:mplayer -quiethttp://www.bbc.co.uk/radio/listen/live/r6_aaclca.pls* FAILS *mplayer -quiethttp://tx.sharp-stream.com/icecast.php?i=planetrock.mp3* WORKS *
|
mplayer failing to play on-line .pls files when started from cron
|
To get the list of PHP processes see this question:How to get list of running php scripts using PHP exec()?Another option is that you can acquire a lock of the file and then check it before running:
for example:$thisfilepath = $_SERVER['SCRIPT_FILENAME'];
$thisfilepath = fopen($thisfilepath,'r');
if (!flock($thisfilepath,LOCK_EX | LOCK_NB))
{
customlogfunctionandemail("File is Locked");
exit();
}
elseif(flock($thisfilepath,LOCK_EX | LOCK_NB)) // Acquire Lock
{
// Write your code
// Unlock before finish
flock($thisfilepath,LOCK_UN); // Unlock the file and Exit
customlogfunctionandemail("Process completed. File is unlocked");
exit();
}Basically in the above example you are first checking if the file is locked or not and if it is not locked (means process is completed) you can acquire lock and begin your code.Thanks
|
I have a cronjob that runs a PHP file that runs a DAEMON written in PHP, but I only want to run the DAEMON if no other instances of it are running, how can I get a list of PHP processes running in order to find if my DAEMON is running. I thought about some kind of exec that will generate a list that I can store in an array. Any ideas? thanks
|
How to get list of PHP processes running on server with PHP
|
You are on the right track. To fire a python script everynhours, do this:* */n * * * python /home/pi/Desktop/myProg.pyThat's it. Make sure that you are editing the sudo level crontab, which is accessed viasudo crontab -e.Your code would actually have the script run at 2 am every day - it technically says "run whenever the hour is equal to2".* */n * * *says "run whenever the hour is divisible byn". A GREAT resource on crontab can be found here:Schedule tasks on Linux using crontabLogging the output is also easy. If you had a log file on your desktop called myLog.log, you would add>> /home/pi/Desktop/myLog.logto end of the crontab entry. That would make the entry look like this:* */2 * * * python /home/pi/Desktop/myProg.py >> /home/pi/Desktop/myLog.logEDIT(thanks to @Iamreck): Another option for outputting to a file is with sys.stdout. This would accomplish the same goal. To do it this way, add the following to your Python script:import sys
sys.stdout = open("myLog.log","w")
sys.stderr = open("myLogErr.log","w")
print "stdout test"You would also have to change the working directory to your Desktop when doing this, and this can be done with the top answer atthis SO post
|
I have finished a program in Python and I intend for it to be run from my RPi everynhours. This will be my first time running such program/script in this way and I would like to know if there is anything I should know/have written into the script before I add it to my crontab?I'm also not sure how such an entry in the crontab would look. Do I write something like:* 2 * * * pi `python /home/pi/Desktop/myProg.py`With back-ticks around the command or would I launch myProg.py from within a shell script that I would call from the crontab?* 2 * * * pi /home/pi/Desktop/launchMyProg.shAlso, I had someprintstatements in the program that I commented out as they were mainly for debug during writing it, but on second thoughts it would be useful for me to have these for debug info but directed to the/var/log/messagesor other log file which I can monitor withtail -f /var/log/messagescommand.How would I do that exactly? Thanks.
|
Python script from Cron
|
You can use Spring environment profiles(example using annotations,example using xml), so you can have different profiles for development, testing, production, etc. And these are set via properties (spring.profiles.active).
|
I am scheduling a task using Spring Framework and have a cron value set through an environment specific property file. I am looking for a way to disable this task through a property so that only certain environments run this task.<task:scheduled-tasks>
<task:scheduled ref="theClass" method="theMethod" cron="${scheduler.cron}" />
</task:scheduled-tasks>
<bean id="theClass" class="com.test.TheClass" scope="prototype" />
|
Disable a Spring Scheduler Task via Property
|
Are all other warningsDeprecationWarnings? Run the script like this:python -W ignore::DeprecationWarning thescript.pyIf you want to ignore all warnings, usepython -W ignore thescript.pyTo ignore warnings system- or cron-wide, set the env variablePYTHONWARNINGS:PYTHONWARNINGS=ignore::DeprecationWarning
# or PYTHONWARNINGS=ignoreDocumentation:The -W optionandPYTHONWARNINGS.What python version do you use? DeprecationWarning should be ignored by default in 2.7.
|
I have a lot of python scripts which generate/home/intranet/public_html/intranet/bin/utils.py:172: DeprecationWarning: os.popen4 is deprecated. Use the subprocess module.
fin, fout = os.popen4(cmd)and other warnings.Is there a way to hide them system- or cron-wide?Thanks!
|
Suppressing python warnings system-wide or cron-wide
|
The format of a number printed with%'ddepends on the current locale, not (necessarily) on whichprintfcommand you're using.If your script is as you've shown us, you're invoking/usr/bin/printf.On my system:$ echo $LANG
en_US.UTF-8
$ printf "%'d\n" 123456
123,456
$ /usr/bin/printf "%'d\n" 123456
123,456
$ LANG=C printf "%'d\n" 123456
123456
$ LANG=C /usr/bin/printf "%'d\n" 123456
123456
$Bash's built-inprintfand/usr/bin/printf(from GNU Coreutils) behave consistently.You probably need to set$LANGin your script to get the behavior you want.The%'dformat is documented in theGNU libc manual:'Separate the digits into groups as specified by the locale specified
for theLC_NUMERICcategory; *note General Numeric::. This flag is a
GNU extension.
|
I have a nightly report that is executed by cron with the following lines in it:PRINTFX="/usr/bin/printf"
<snip>
${PRINTFX} "%-11s %-11s %'d\n" ${F1} ${F2} ${F3}Crontab entry:[ca-adm@homwpspect01 ~]$ crontab -l
55 01 * * * /usr/local/sbin/CRONSQLEventsMy Issue is that if I run this manually as root (i.e. with my login env settings), I get this [CORRECT] output:Date Event Count
2013-02-19 0x00010802 516,616
2013-02-19 0x00010D66 351,840
2013-02-19 0x00010D67 351,533When run by cron as another user, I get [InCorrect]:Date Event Count
2013-02-19 0x00010802 516616
2013-02-19 0x00010D66 351840
2013-02-19 0x00010D67 351533If it is run by cron, the comma is MISSING from the numeric output. I remember reading something about use of printf being ambiguous because there is a bash internal function, but there is also an external in /usr/bin:[root@homwpspect01 sbin]# which printf
printf is a shell builtin
printf is /usr/bin/printfCan someone tell me how to avoid this issue with cron versus logged in execution ?
Especially given that I am specifying the /usr/bin/printf in the script anyway ?Thanks in advance,
Don
|
env issues when running cron bash script
|
Since you lose the ability to specify ranges once you specify days, I think the best option would be to supply the time (every 10 minutes from 07:00 to 15:00) and then have a check in your script itself that checks the current date to determine if it is a weekday or not. You could do that with something simple like :>>> import datetime
>>> today = datetime.datetime.today()
>>> today.weekday()
1Where0= Monday,1= Tuesday, etc. If your cron verified that the current weekday wasin (5, 6), then you could simply exit your program. One way of structuring this could be to link your cron to a simple function that checked the day - if a weekday, then your main function is called; if not, it ends. There may be a better way, but that's the best I can come up with right now :)
|
I went to Google's site oncron'sand it looks like I can not set a cron job to run Mon-Fri every 10min from 07:00 to 15:00. Therefore I have 2 questions:1) Can I have the cron job run every day, then have it not run on Sat and Sun, and then resume again on Mon-Fri?2) If I can't do the first option, is there a way to have a cron job quit automatically?Im am doing this in Python. If this isn't possible, is there a page I can look to for help?
|
Seting up a cron job in google app engine
|
Use theatcommand from the python script. See the documentationhere.
|
I've been looking around for a while for the best way to do this, but not really getting very far. I have a python script that is running several times a day on a cron, this script determines the times and dates that another script needs to be scheduled to run. The times, dates and durations that this script need to run on varies dramatically, and they are one-off events.My problem is how to actually schedule these events. Can anyone advise a suitable python or linux method?ThanksUPDATE: Thanks chaps for the prompt.For anyone else searching this, this is what I did, for script foobar.py to run at 9.15am on Jul 14th:import subprocess
subprocess.Popen(['python foobar.py | at 9.15am Jul 14',], shell=True)
|
Scheduling Python Scripts on Linux
|
The better version is now to usewp-cli. The latest version (0.9.2.8) is compatible with this plugin. Just run this command from anywhere in your wordpress directory :wp w3-total-cache flush
|
Ok. I'm really stumped on this one.Basically, I need to call a function for the Wordpress plugin W3 Total Cache as part of a cron job in crontab. I'd like to automatically clear the entire page cache nightly.Here's the code that works fine within wordpress that I need to call:if (function_exists('w3tc_pgcache_flush')) {
w3tc_pgcache_flush();
}I'm currently using the following script:#!/usr/bin/php
<?php
define('DOING_AJAX', true);
define('WP_USE_THEMES', false);
$_SERVER = array(
"HTTP_HOST" => "http://example.com",
"SERVER_NAME" => "http://example.com",
"REQUEST_URI" => "/",
"REQUEST_METHOD" => "GET"
);
require_once('/path-to-file/wp-load.php');
wp_mail('[email protected]', 'Automatic email', 'Hello, this is an automatically scheduled email from WordPress.');
if (function_exists('w3tc_pgcache_flush')) {
w3tc_pgcache_flush();
}
?>and the command line:php -q /path-to-file/flushtest.phpI used the wp_mail function to test and make sure I'm getting something.The script is working fine except that the page cache is never flushed. I get the email and there aren't any errors in the log either.Any ideas?Thanks for your help.
|
Run W3 Total Cache Function with Crontab
|
I think you will need 2 lines to achieve what you need:30 6-11 * * * /path/to/your/command
0 7-11 * * * /path/to/your/command
|
Can I schedule job in cron format so that it runs every 30 minutes from 6:30 am to 11:30, every day? How?
|
Cron - schedule job every 30 minutes, starts half past full hour
|
Turns out this is quite easy, and can be achieved by usingcustom django-admin commands. You basically add amanagement/commandsfolder to the project, and add a python script to that folder with a specific structure (see documentation). Say you call the filecron.py. Then a cron can be configured as such:*/30 * * * * python3.8 /var/djangoproject/manage.py cron
|
I have been trying to run some code as a cron job using Django. There are anumberofpackagesthat help do this, but they do not seem to support the latest Django version (4.0). Instead of continuing to search for packages, I was wondering if it is possible for me to simply write a python script within my Django folder structure, and manually configure a cron job to run this. Something like setting up:*/30 * * * * python3.8 /var/djangoproject/crons/cron.pyIs this possible? Is there any drawback or risk in doing it like this instead of using a package that is made for this? I don't see anyone recommending this so before implementing it I wanted to see if this is a good idea.
|
How to manually create a cron job to run a Django script?
|
in yaml file, securityContext was missing, i added that and now it is working fine. Below one is the updated yaml fileapiVersion: batch/v1beta1
kind: CronJob
metadata:
name: abc-cron-job
spec:
schedule: "10 * * * *"
jobTemplate:
spec:
template:
spec:
securityContext:
runAsGroup: 3000
runAsUser: 3000
containers:
- name: abc-cron-job
image: docker.repo1.xyz.com/abc-services/abc-application/REPLACE_ME
imagePullPolicy: Always
env:
- name: spring-profile
valueFrom:
configMapKeyRef:
name: spring-profile
key: ENV
securityContext:
privileged: false
restartPolicy: OnFailure
|
container "abc-job" in pod "abc-job-manual-h9k-vbbzw" is waiting to start: CreateContainerConfigErrorError: container has runAsNonRoot and image will run as root (pod: "abc-job-manual-h9k-xyz-ns-nonprod(e38ece94-b411-4d70-bc29-3711f36cfe45)", container: abc-cron-job)Below image is from cluser in pod detailsbelow is my yaml file for cronjobapiVersion: batch/v1beta1
kind: CronJob
metadata:
name: abc-cron-job
spec:
schedule: "10 * * * *"
jobTemplate:
spec:
template:
spec:
containers:
- name: abc-cron-job
image: docker.repo1.jkl.com/xyz-services/abc/REPLACE_ME
imagePullPolicy: Always
env:
- name: spring-profile
valueFrom:
configMapKeyRef:
name: spring-profile
key: ENV
restartPolicy: OnFailure
|
container "" in pod "" is waiting to start: CreateContainerConfigError
|
As I can format here better now as an answer:If might be that cron simply picks the wrong interpreter in your case. A simple solution is to provide the full path to it, you can find it with:md@gw1:~$ type python2.7
python2.7 is /usr/bin/python2.7
md@gw1:~$Now use inside your crontab:0 12 * * * /usr/bin/python2.7 your_script.pyAlternatively use a so called shebang:md@gw1:~$ cat your_script.py
#!/usr/bin/python2.7
print "hello"
md@gw1:~$ chmod +x your_script.py
md@gw1:~$ ./your_script.py
hello
md@gw1:~$The first line in your_script.py and the chmod made it executeble and will use the correct interpreter.
|
I have a Python script using requests module. It works on my desktop (Windows), and works when I run it manually on my VM (Ubuntu 14.04 / python 2.7.14).
However, when the exact same command is scheduled as a CRON job on the same VM, it's failing.The offending line seems to be:index_response = requests.get(my_https_URL, verify=False)The (slightly redacted) response is:(<class 'requests.exceptions.SSLError'>, SSLError(MaxRetryError("HTTPSConnectionPool(host=my_https_URL, port=443): Max retries exceeded with url: / (Caused by SSLError(SSLError(1, '_ssl.c:510: error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure'),))",),), <traceback object at 0x7f3d877ce5f0>)HTTP URLs don't seem to be affected, and indeed some HTTPS URLsareworking... (I think it's domains requiring SNI which are not working).I've tried addingverify=False, and even running the CRON script as sudo, but no update.
It originally failed when I was running it manually, but I then installed python2.7.14 (in addition to python 2.7.6), which resolved the manual issue. To add some further complexity, the script is being triggered by another one usingexec(the test runner runs various tests scripts including this one) - could this be related?I didn't have this problem in urllib2, but would prefer not to move back from requests to urllib2 if I can help it...
|
Python SSLError on Ubuntu, but only when run from a CRON
|
For the first immediate run, just execute the command manually. Then set your cron up like this to have it execute continuously every 4th hour0 */4 * * * yourCommandThis will run yourCommand every 4 hours (00:00, 04:00, 08:00......)
|
How do you write a cron job which immediately run, then run on every hour divisible by 4? Say I started the script at 13:25, the job fires up right away, then the next run would be at 16:00, 20:00, 00:00 and so on.
|
Run immediately then every 4 hours in cron
|
The queue serializes the Job before sending it to the queue and unserializes it when it's handled. You'll need theApp\Jobs\StoreAppliedjobon the location where it's being handled.
|
The problem is that I have two Laravel projects working on Laravel5.1and5.3and sharing common database. Both projects are placed on different subdomains up and running.
Now while usingqueuedriver asdatabasefor both projects I am using5.3demon to run on5.1queued jobs I am getting following error.PHP Fatal error: method_exists(): The script tried to execute a method or access a property of an incomplete object. Please ensure that the class definition "App\Jobs\StoreAppliedjob" of the object you are trying to operate on was loaded _before_ unserialize() gets called or provide a __autoload() function to load the class definition in /Applications/MAMP/htdocs/admin-badiyajobs/vendor/laravel/framework/src/Illuminate/Queue/CallQueuedHandler.php on line 83
[Symfony\Component\Debug\Exception\FatalErrorException]The5.1queue is working fine when run with queue listener on5.1. Note that I can't use separatecronon both projects to process queue as that will mess up everything. Please suggest what should I do ?
|
PHP Fatal error: method_exists(): The script tried to execute a method or access a property of an incomplete object Laravel 5.3
|
/usr/bin/php-cli /home/bharat2016/public_html/artisan schedule:run >/dev/null 2>&1php-clineeds to be written for accessing php command. I found it after lots of efforts so I want to give it an answer to be useful to other users who might face this issue in future
|
I am building an application in Laravel 5.2 and I am in need to build few CronJobs so I have written a command in my GoDaddy's cPanel like* * * * * /usr/bin/php -q /home/bharat2016/public_html/artisan schedule:runBasically I want to write php artisan schedule:run and it's working perfectly fine on my local but it's not running in my GoDaddy Hosting. Is the php path is perfect? PPlease let me know if there needs any other command then thisNOTE:
I have tried* * * * * /usr/bin/php /home/bharat2016/public_html/artisan schedule:runand* * * * * /usr/bin/php /home/bharat2016/public_html/artisan schedule:run >/dev/null 2>&1but it's not working.Any help will be appreciated!
Thanks in advance.
|
CronJob not starting in GoDaddy Shared hosting
|
+50First off, it's alway better to include thefullpath of your script inside the cron tab.30 3 * * * /opt/btg/back-to-git >/dev/null 2>&1Replace/opt/btg/back-to-gitwith the absolute path to your script.
Then try to not throw away the output which my contain errors:30 3 * * * /opt/btg/back-to-git &>/home/your_user/btg.logThis way you can detect errors while cron is processing the script.Your last comment indicates that there might be auth problems with bitbucket. To make sure you push in the right way I would advise to always write out the full target for git inside scripts. So try to usegit push --all origininstead ofgit push all;The please check your git settings to usesshand nothttpswhen pushing to bitbucket.You can also specify the host and ssh key to use in your/root/.ssh/configHost bitbucket
HostName bitbucket.org
User YOUR_USERNAME
IdentityFile /root/.ssh/id_rsa
IdentitiesOnly yes
|
I have a cron job setup to run a bash script to push to Git every night.The cron job was setup as root, and I have set my git credentials via:git config credential.helper storeas per:Git push: username, password, how to avoid?(second answer)The code for the bash script is pretty simple#!/bin/bash
# Nightly push to Bitbucket
# Set some variables
DAY=$(date +%F);
# Make sure we run as root
if [ "$(whoami)" != "root" ]; then
echo "Only root can do this.";
exit 1;
else
# Make sure we are in the right directory
cd /hosting;
# Now add any changes
git add .;
# Now commit
git commit -m "$DAY Nightly";
git push all;
fi;And runs without a hiccup so long as I log into the server and run it as root.However, it does not run at the specified time.Crontab -e is set with:30 3 * * * back-to-git >/dev/null 2>&1What can I do to get it to work?
|
Cron job Auto-Push to Git Issue
|
Try something like this:<route>
<from uri="quartz2://timer1?cron=0+30+5+*+*+*">
<from uri="quartz2://timer2?cron=0+30+11+*+*+*">
<from uri="quartz2://timer3?cron=0+00+15+*+*+*">
<from uri="quartz2://timer4?cron=0+00+21+*+*+*">
<to uri="...">
</route>It's not possible today in the quartz component to provide a custom trigger, and the quartz cron trigger didn't support what you want. Just create a route with multiple consumers.
|
I have to execute/run same task in different fixed times every day. The intervals between the time is not same.for example I want to run a router 05:30, 11:30, 15:00, 21:00.I got lot of apache camel example with scheduler, quartz. But all are with static time interval or only one time configurable.Is there way to configure in apache camel ?
|
Apache Camel Schedule multiple times a day
|
Adding the below to my ApplicationContext resolved the issue..@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
|
I was trying to define the cron details in my spring @Scheduled method@Service
@PropertySource("classpath:application.properties")
public class CacheRefreshService {
@Scheduled(cron = "${api.refresh.cron}")
public void refreshJob() throws Exception {
LOGGER.info("Started Refresh");
//do something
}
}And in my application.properties#Refresh
api.refresh.cron =0 29 11 * * ?When I define the cron details along with @Scheduled, it is running fine. But when I do this, it is not able to read the value from the properties file and the below error is thrown.Caused by: java.lang.IllegalStateException: Encountered invalid @Scheduled method 'refreshJob': Cron expression must consist of 6 fields (found 1 in "${api.refresh.cron}")Any suggestions please?
|
Spring @Scheduled cron details from property file - Exception
|
I was able to solve my problem. I changed the cronjob tasks in direct admin as suggested by the module.The setup is as followed (keep in mind that AOE_Scheduler has to be installed:* * * * * /bin/bash path_to_root_site/public_html/scheduler_cron.sh --mode always* * * * * /bin/bash path_to_root_site/public_html/scheduler_cron.sh --mode default
|
I can't find a proper solution for sending order confirmation emails. Invoice emails are being send after a purchase is completed. The only problem is that the order confirmation fails to send.In my database i can see that the order email is in the queue (core_email_queue). Processed_at is NULL.I tested the cronjob with direct admin, and i am able to call a script that will send me a random email, so that is working.Despite all that, i see that no heartbeat task is found with AOE_Scheduler.Any ideas? It worked before and suddenly stopped working
|
Magento 1.9.1.0 Order confirmation not send
|
The second Tuesday of the month will occur between the 8th and the 14th inclusive, so set the day-of-week field to 4 (Thursday), and the day-of-month field to 10-16 (that is, a range adjusted to be two days after the range of the month's second Tuesday).
|
I want to schedule to run a shell script on a Thursday which comes after the second Tuesday of every month. How to schedule this in crontab?
|
how to schedule to run a shell script on a particular day of a month
|
The following applies to Prestashop's "native" cronjob handler (version 1.3.2)You can make your module auto-install a cronjob by ensuring the following:Register to the hookactionCronJobProvide a public methodgetCronFrequency()Provide a public methodactionCronJob()getCronFrequencyshould return an array that looks like this:array('hour'=>1, 'day'=>-1, 'month'=>-1, 'day_of_week'=>1);The-1values are the equivalent of the*in Unix-style cronjobs.Be aware though, that "Basic" mode cron jobs get triggered by a webservice hosted by Prestashop themselves. This means your website has to be publicly accessible so you can't easily test this on your typical localhost development environment.Advanced cronjobs are not registered at Prestashop's webservice, so you can trigger them yourself through your own crontab manager.
|
I'm trying create simple new cron job for my module in Prestashop. Everywhere I see to do it I must define my cron in admin panel. But it seems stupid, because I won't write to each person which download my module to activate this cron manually.
I wrote cron jobs for wordpress and magento without problem, but in Prestashop I can't find any tutorial when would be described this process. It is possible to write and activate cron automatically?Thanks
|
How to create cron job without admin panel in Prestashop
|
You need a listener for reading theJSON payloadsent by awebhookset on your GitHub repo.See for instance "webhooker": An application to run shell commands on incoming WebHooks from Github.
|
I'm looking to monitor a GitHub repo for changes. I want to do this as simple as possible (ie, no Jenkins). Perhaps a cron job that runs every so often, and when changes are detected in the repo/branch, run a build.What's the best way to do this?
|
How to monitor GitHub repo for changes?
|
It might be that you just mixed up your arguments?mutt -s "Test from mutt" -a /tmp/file.jpg --[email protected]< /tmp/message.txtIf that doesn't work check your environment variables. You don't get a login shell during cron execution, so you might be missing EMAIL, MAIL, MAILDIR, REPLYTO or some of those environment variables your mutt configuration depends on.
|
I want to use cron to execute a mutt script to send an email periodically. I've got the mutt installed and successfully sent emails by executing the mutt script like:#!/bin/bash
mutt -s "Test from mutt"[email protected]< /tmp/message.txt -a /tmp/file.jpgThen I tried to execute this script in cron, but cron doesn't send the email as I expect. I'm sure that my cron is working because I used cron to execute another email tool:#!/bin/bash
mail -s "Hello" "[email protected]"This time cron did the work and sent the email at the expected time. So I'm thinking there maybe some problem when using cron to execute mutt command. Can anyone help me?
My cron script is like following:15 * * * * bash /Users/DengWenzhe/Study/SportsMedia101/sendEmail.shEDIT:
The reason I want to use mutt is that I want to send email with attachment, which 'mail' version couldn't. If anyone know a command email tool that can work well with cron, that would also be helpful.
|
How to use cron to execute mutt to send email?
|
Your Python script might be missing permission to execute, or missing shebang on the first line to be interpreted by Python.Easy solution is to change:somepath/check_crack.pyinto:python somepath/check_crack.pyor even to:/usr/bin/python somepath/check_crack.pyThis way cron will know, that it shall be interpreted by Python and run it.
|
I want to run a python script every so often on my web hosting, using cpanel, so it looks like…However, every single formatting and file path I've tried returns with it saying no such file exists, when in fact I know for sure that it does.Any help?If it means anything, I'm running on shared hosting with namecheap.
|
How to create a cronjob for a python script in cpanel?
|
So we ended up using a slightly different format to get this up and running. For our uses, we excluded the time zone info, but it works with it as well.module.exports = (robot) ->
cronJob = require('cron').CronJob
new cronJob('0 */1 * * * *', everyMinute(robot), null, true)
everyMinute = (robot) ->
-> robot.messageRoom '#billing', 'hey brah!'If anyone has this running with code closer to the examples, feel free to answer.
|
I've been unable to properly setup Hubot and node-cron to execute tasks within my IRC channels.This page shows how I initially setup my code:https://leanpub.com/automation-and-monitoring-with-hubot/read#leanpub-auto-periodic-task-executionHere is the link to node-cron:https://github.com/ncb000gt/node-cronI'm thinking I'm running into an issue with Hubot's IRC adapter, but I'm not sure. Any advice and code examples would be welcome.Here is where I've ended up in testing:module.exports = (robot) ->
cronJob = require('cron').CronJob
tz = 'America/Minneapolis'
new cronJob('30 * * * * *', testFunction, true, tz)
room = '#support' #not used in this case
testFunction = ->
robot.send "I work!"or per example from LeanpubtestFunction = ->
robot.messageRoom room "I work!"cron jobs setup after Hubot is running work fine:Hubot new job "<crontab format>" <message> - Schedule a cron job to say somethingThank you again, all!
|
How to use Hubot and node-cron with the IRC adapter
|
liebig/croncomes with'preventOverlapping' => trueenabled in its config file. This prevents cron job from running again, when it is already running (i.e. previous cycle not finished yet).To do thiscronpackage create file namedcron.lockinapp/storagefolder. Sometimes due to file permission issues, this file does not get deleted even after successful cron job completion, thus preventing any future cron job runs.Check the file permissions in app/storage directory. Ifcron.lockexists delete it and let the cron job run again.Hope this helps you.
|
I am using theliebig/cronpackage for cron job in my project,I followed the installation process of this package properly,And here is my codeRoute::get('/cron/run/cronjob123', function () {
Cron::add('example1', '* * * * *', function() {
echo 'success'; die;
return null;
});
$report = Cron::run();
});Right now i am working in localhost so when i enter theurlmyproject/cron/run/cronjob123It should displaysuccessBut directly the execution flow is going to$reportAnd the the$reporthas this result,Array ( [rundate] => 1398489241 [runtime] => -1 )I am not getting where i am going wrong.
|
Cron Job Laravel 4
|
Ijustran into this, and adding the scheduling to Bootstrap.groovy worked just fine. In your MyJob class, set triggers to an empty closure:class MyJob {
static triggers = {
// Job is scheduled in Bootstrap.groovy so that it can be externalized
}
def execute() {
println "do some work"
}
}Then in your Bootstrap.groovy file, set it up like this:class BootStrap {
def grailsApplication
def init = { servletContext ->
MyJob.schedule(grailsApplication.config.myJob.cron)
}
}
|
This question already has answers here:Quartz job triggering from Config.groovy(2 answers)Closed10 years ago.Am using the Quartz plugin for Grails and have a simple job:class MyJob{
static triggers = {
cron name: 'MyJobTrigger', cronExpression: '0 0/1 * * * ?'
}
def execute(){
println "do some work"
}
}All works fine, job fires off every minute as expected.Now I want the want the cron expression to be property driven so I can override in different environments. So Config.groovy contains the default value:myJob.cron = '0 0/1 * * * * ?'And I change my class to have:GrailsApplication grailsApplication
static triggers = {
cron name: 'MyJobTrigger', cronExpression: grailsApplication.config.myJob.cron
}When I run my code, I get this error:Caused by MissingPropertyException: No such property: grailsApplication for class: MyJobAssuming this is something to do with the way the MyJob class is loaded/initialised, the static triggers created before the GrailsApplication is injected??? This use of GrailsApplication is the usual way I get project properties.How else can I have a property driven cron trigger?
|
Grails - using property value for cron expression in scheduled job [duplicate]
|
grep -e "string1" -e "string" ./my_fliles* |
awk -F " " '{ n = split($1,RES,"/"); OUT=RES[n];
for( i=2; i<=NF; i++) { OUT=OUT" "$i } print OUT;}'In thegrepresults, the path and string are separated by a' '(space)/home/username/scriptfolder/logs/filename1 string1You can use the-Fflag to set the field separator used byawk, the default separator is space.
This splits the input into$1, $2, . . . , $NFfields.awkhas a predefined functionsplit.n = split( String, A, [Ere] )This function splits the string specified by theStringparameter into array elementsA[1], A[2], . . ., A[n], and returns the value
of thenvariable. The separation is done with the extended regular expression specified by theEreparameter or with
the current field separator (theFSspecial variable) if theEreparameter is not given. The elements in the A array are
created with string values, unless context indicates a particular element should also have a numeric value.for( i=2; i<=NF; i++) { OUT=OUT" "$i }will concatenate the original input fields into the variable OUT separated by space. This is to ensure that we do not miss any fields due to spaces in the searched stringstring1orstring2. Note that the loop started withi=2The final output will look like below:filename1 string1
filename1 string2
filename2 string1
|
I have a script that works great but in that script I am using grep to extract two linesgrep -e "string1" -e "string" my_fliles* >> //destinationThe output of that looks goodfilename1 string1
filename1 string2
filename2 string1
filename2 string2
filename3 string1
filename3 string2That is the desired effect but in order to get it to work in a cron job I have to specify the full path to my_filesgrep -e "string1" -e "string" /home/username/scriptfolder/logs/my_fliles* >> //destinationThat creates output like/home/username/scriptfolder/logs/filename1 string1
/home/username/scriptfolder/logs/filename1 string2
/home/username/scriptfolder/logs/filename2 string1
/home/username/scriptfolder/logs/filename2 string2
/home/username/scriptfolder/logs/filename3 string1
/home/username/scriptfolder/logs/filename3 string2I want the filenames and the string outputs but not the path.
I tried removing the path and specifying the path in the script withexport PATH=$PATH:/home/username/scriptfolder/logs/but that did not work.
anny suggestions?
|
Need to remove the path from the output of a grep but not the file
|
Here's what i came up with. Instead of populating the dates every day, i'm going to set my cron to run on the first of every month and just loop for every day in that month. This will include feb 29th on leap years.startDate = (Time.now.beginning_of_month.to_date) + 2.years
endDate = ((Time.now.beginning_of_month.to_date) + 2.years).end_of_month
startDate.upto(endDate).each do |d|
5.times do
timeslot = Timeslot.create
timeslot.location_id = 1
timeslot.timeslot = "#{d} 09:00:00"
timeslot.save
timeslot = Timeslot.create
timeslot.location_id = 1
timeslot.timeslot = "#{d} 11:00:00"
timeslot.save
timeslot = Timeslot.create
timeslot.location_id = 1
timeslot.timeslot = "#{d} 13:00:00"
timeslot.save
timeslot = Timeslot.create
timeslot.location_id = 1
timeslot.timeslot = "#{d} 15:00:00"
timeslot.save
end
end
|
Basically I have an app where a user can select a timeslot for any day from now until 2 years from now. i'm creating a rake task that runs every day to add a record to my database for 2 years from now so that tomorrow, there will still be 2 years worth of timeslot choices.With my current logic, i'm curious as to what will happen when there's a leap year, and is there a way to make this more robust to handle leap years correctly? I'm afraid that i'm either going to end up with a day that gets missed completely, or a day that gets duplicated.task :generate_timeslots => :environment do
startDate = Time.now.to_date + 2.years
endDate = Time.now.to_date + 2.years
startDate.upto(endDate).each do |d|
5.times do
timeslot = Timeslot.create
timeslot.location_id = 1
timeslot.timeslot = "#{d} 09:00:00"
timeslot.save
timeslot = Timeslot.create
timeslot.location_id = 1
timeslot.timeslot = "#{d} 11:00:00"
timeslot.save
timeslot = Timeslot.create
timeslot.location_id = 1
timeslot.timeslot = "#{d} 13:00:00"
timeslot.save
timeslot = Timeslot.create
timeslot.location_id = 1
timeslot.timeslot = "#{d} 15:00:00"
timeslot.save
end
end
end
|
Rails cron job runs every day to create database record 2 years from now. How to account for leap years?
|
Using Cron + PHP CLI to execute the script:Do not put that file under webroot.Using Cron + Wget to request the script:Pass a secret key to your script via post; check that key in your script. Example:Content of key.txt which resides on the server outside wwwroot:key=helloWget command linewget --post-file=key.txt http://example.com/cron.phpPHP scriptparse_str(file_get_contents("key.txt"), $array);
if($array != $_POST)
die("does not match");
|
This question already has answers here:Run a script.php on cron job on linux/apache server but restrict public access to the php file(4 answers)Closed11 years ago.I need advise regarding safeguarding a file i created that runs on via cronjobs.Currently, i'm using HTTP_referrer from preventing direct access from unauthorised person. But will this also prevent my cron jobs from executing it as well.I inserted the following code at the top of my script:if(empty($_SERVER['HTTP_REFERER'])){
echo 'Restricted Access';
exit;
}Is this secure and will it prevent access from my cron? Any help appreciated. Thanks.
|
Restricting file running via cron job from direct access [duplicate]
|
Infinite looping applications are usually called daemons. They are system services that offer some kind of constant processing and/or the readiness to accept some potential incoming processing activities.Gearmanis a system daemon you can install than can handle various tasks you give it. It's a complex tools that allows many things but it could be used to implement your necessities.PHP::Gearmanis a Gearman client that talks to the Gearman daemon and sends tasks to the daemon specifying the conditions under which the task must be executed.The limitations that @Jeffrey emphasized about PHP are true because PHP was designed as a share nothing architecture (one page load equals one script execution - each page load works under its own data context).PerhapsSystem Daemon(a pear package) may assist in overcoming some or all of the limitations mentioned above. I haven't used it so I can't tell you much more about it but it's as good a place to start as any.
|
Running an infinite loop in cron job.Suppose, i have written a php based script to run on my server computer using cron job, and i want to use infinite loop in that php script.Any ideas for running an infinite loop in cron job.
|
Running an infinite loop in cron job
|
This will flood the crontab and will do no good, especially if you get more jobs in the future. I would recommend to use just one script running all 15 minutes and check the time inside the script. Process your links according with wether it's 0, 15, 30 or 45 minutes.Once you get more links you can either process more of them in each run or lower the time between calls by simply changing one line in the crontab and your statement switch.
|
I have a situation where there are thousands of products where each product price continuously check and up to date with other sites. For fast processing i created multiple links. each link process 50 records only. and divided all links on 5 servers for fast processings.I setup cron job for each link which should be processed after every 12 hours. but there should be 15 min gap between two link processing time on single server.As there are huge no of links generated manually. (about 230 links or more), it can't be easy for me to setup cron job for each link manually.For this reason i want to write dynamic php script to generate 230 crone job links.I write txt file and generate script for cron job about 230 links here is sample example.0 0,12 * * * /usr/local/bin/php -f http://xxx.us/amazon/proc.php? id=1&size=50
15 0,12 * * * /usr/local/bin/php -f http://xxx.us/amazon/proc.php?id=2&size=50
30 0,12 * * * /usr/local/bin/php -f http://xxx.us/amazon/proc.php?id=3&size=50
45 0,12 * * * /usr/local/bin/php -f http://xxx.us/amazon/proc.php?id=4&size=50
.....
230 crone job linksIs there any way i can execute dynamically generated script on server to automatically install all cron jobs instead of doing it manually which took lot of time even in start and also if in case i need modification in future.
|
Cron job setup and automatic execution on server
|
In your app, you can create a folder calledmanagementwhich contains another foldercommandsand an empty__init__.pyfile. Insidecommandsyou create another__init__.pyand a file where you write your custom command. Let's called itrefresh.py:# refresh.py
from django.core.management.base import BaseCommand, CommandError
from main.models import * # You may want to import your models in order to use
# them in your cron job.
class Command(BaseCommand):
help = 'Posts popular threads'
def handle(self, *args, **options):
# Code to refresh cacheNow you can add this file to your cron jobs. You can take a look at thistutorialbut basically you use crontab -e to edit your cron jobs and crontab -l to see which cron jobs are running.You can find all of this and more in theDjango documentation.
|
I've had some trouble trying to reset my cache every hour for a particular django view.Right now, I am using the cache_page decorator to cache my view using Memcached. But the cache expires after a while and the request is uncached from some users.@cache_page(3600)def my_view(request):...How do I write my own django manage.py command to refresh my cache for this view every hour from cron?In other words, what do I put in my refresh_cache.py file mentioned in the answer here:Django caching - can it be done pre-emptively?Thanks!
|
Cronjob to periodically refresh cache for django view
|
Probably the temp file was created by php script(apache user) and you want to read it from cron job (root user). Temp files are not readable from one users to others for security reasons.You have to change your cron job to be executed by apache user, or you can alter the permissions of the temp file to be readable for everyone, but this is not recommended as any other procesess could read the file.
|
I'm using a ftp upload script to transfer one server to another. It works fine in a browser window, and works great from an ssh command line by running:
php /var/www/vhosts/domain.com/httpdocs/ftp_shell.phpbut when I run the exact same command from a cron, I get this:PHP Warning: ftp_get(ftp.tmp): failed to open stream: Permission denied in /var/www/vhosts/domain.com/httpdocs/ftp_shell.php on line 516
PHP Warning: ftp_get(): Error opening ftp.tmp in /var/www/vhosts/domain.com/httpdocs/ftp_shell.php on line 516I looked on line 516, which is:if((ftp_get($ftp_from,"ftp".$tmp.".tmp",$fname,FTP_BINARY) ||
ftp_get($ftp_from,"ftp".$tmp.".tmp",$fname,FTP_ASCII)) &&
(ftp_put($ftp_to,$fname,"ftp".$tmp.".tmp",FTP_BINARY) ||
ftp_put($ftp_to,$fname,"ftp".$tmp.".tmp",FTP_ASCII)) &&
ftp_site($ftp_to,"chmod ".base_convert($chmod,10,8)." $fname") &&
f_size()&&unlink("ftp".$tmp.".tmp")) {echoout(" (".$size_b." bytes) ok<br>");$count_f++;}I know that it's writing the file to a temp file, but why would it allow me to do it in the browser and command line, but not a cron?
|
php ftp_get() returns permission denied
|
At a guess,notify-sendis a program which uses X; in which case, it needs to know the display number of the X display to show the notification on. When you start a terminal in X, that's set automatically, but a crontab doesn't have that environment.As a simplistic start, try changing your crontab line to this:* * * * * DISPLAY=:0.0 /home/noob/test.sh
|
I am trying to setup a cronjob to execute a script every minute.My test.sh script:#!/bin/bash
notify-send helloI have made the above script executable.Here is mycrontab -efile's outputhttp://pastie.org/4316348Now when I see the output ofsyslogit shows that the cronjob is getting executed every minute but I am not able to see my desired output.syslog:Jul 24 17:42:01 noob CRON[5291]: (noob) CMD (/home/noob/test.sh)
Jul 24 17:43:01 noob CRON[5364]: (noob) CMD (/home/noob/test.sh)
Jul 24 17:44:01 noob CRON[5374]: (noob) CMD (/home/noob/test.sh)
Jul 24 17:45:01 noob CRON[5386]: (noob) CMD (/home/noob/test.sh)So, I am wondering what am I doing wrong here and why I am not able to see my desired output(notification).
|
Cron Job in ubuntu not getting the desired output
|
It's going to depend on your host. Cron jobs could really screw stuff up if you're not careful, so a lot of shared hosts don't allow it. You probably need to be on some virtual container (like a VPS, virtuozo, etc.) to do this. This isn't a CodeIgniter issue, but a hosting provider issue. Call them first.
|
I am trying to learn how to do my first cron job using CodeIgniter. In the past, it seemed the only way to do this with CI was to use thewgetcommand instead ofphp.TheCodeIgniter User Guide, however, says that now you can do this from the command line, for example by running:$ cd /path/to/project;
$ php index.php controller methodThis works great using Terminal on my local setup. But when I use a similar command in the cron section of cPanel on my shared hosting, the task just returns the contents ofindex.php.I'm not entirely sure what cPanel does with this command, so unsure as to whether it's using the command line at all.Could someone explain how I might be able to set up a cron job on shared hosting using CodeIgniter please?Here is the example code from the CodeIgniter user guide:tools.phppublic function message($to = 'World')
{
echo "Hello {$to}!".PHP_EOL;
}}
?>
|
CodeIgniter Cron Job on Shared Hosting?
|
Put the source variable in your url path:cron:
- description: update source ABC
url: /cron/ABC/
schedule: every 5 minutes
login: admin
- description: update source XYZ
url: /cron/XYZ/
schedule: every 12 minutes
login: admin
webapp.WSGIApplication([('/cron/([^/]+)/', CronHandler)])
class CronHandler(webapp.RequestHandler):
def post(self, source):
#do something with source variable...
|
I have an application written in Python. It collects and parses data from certain sources (RSS, Atom, Twitter, etc.) and if new data is found, it's saved to a MySQL database.I have many sources defined on the application itself, and not all can be checked on the same time basis because of restrictions (Twitter and its 350 queries per hour, for example), so the idea is to cron them separately by passing sources as arguments.myscript.py --update --source ABC(Fetch, parse, check and save data from ABC source)myscript.py --update --source XYZ(Fetch, parse, check and save data from XYZ source)So far this point, I got that working fine on my local cron, but I'd like to get this running on Google App Engine, withsomethinglike this:cron.yaml:cron:
- description: update source ABC
url: /myscript.py --source ABC
schedule: every 5 minutes
login: admin
- description: update source XYZ
url: /myscript.py --source XYZ
schedule: every 12 minutes
login: adminI haven't found any way to get this done on App Engine Cron documentation. Any workarounds?
|
How to pass arguments to a python cron task on Google App Engine?
|
A recent update of PAM broke cron. Try restarting your computer (or restarting cron withsudo /etc/init.d/cron restart)
|
I have a python script "start.py" that executes well from the command line. There is only one statement in it (print "hello"). EDIT: start.py contains also a working interpreter directive in the first line.As soon as I run the script from a cron job, every time it fires there is a message in syslog:Jun 7 02:57:01 mit CRON[23275]: Module is unknownI tried already to add PATH and PYTHONPATH information to the cron file:$ cat /etc/cron.d/my_cron
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
PYTHONPATH=/usr/lib/python2.6:/usr/lib/python2.6/plat-linux2:/usr/lib/python2.6/lib-tk:/usr/lib/python2.6/lib-old:/usr/lib/python2.6/lib-dynload:/usr/lib/python2.6/dist-packages:/usr/lib/pymodules/python2.6:/usr/lib/pymodules/python2.6/gtk-2.0:/usr/local/lib/python2.6/dist-packages
* * * * * mit /home/mit/dev/start.pyI found several answers and solutions that seem the same but nothing helped me. What am I missing?
|
python script does not run from cron
|
I solve the problem the next way: pass to script environment variables.In case of .htaccess / httpd.conf:SetEnv SITE_NAME x1In case of cron (run a script):#!/bin/bash
export SITE_NAME=x1;
php /pathIn both cases PHP-code to get this environment variable is:getenv('SITE_NAME');x1 — is an example site name.
|
I've got a PHP script that I want to run through cron. It should load different configuration information depending on if the script is running on my local server, the QA server, or the production server. The problem is that when the script is run through cron, it doesn't have any of the identifying $_SERVER information that I use to figure out which environment the script is running on.The only thing I could think of was to have the cron job itself attach a parameter to the script, but I was hoping there was a better way where I wouldn't have to do that. Is there any other way to identify which server the script resides on when running it from cron?Thanks.
|
Get identifying server information when running PHP scripts with CRON
|
Thejobsbuiltin can tell you how many child processes are running. Some simple shell scripting can accomplish this task:MAX_JOBS=2
launch_when_not_busy()
{
while [ $(jobs | wc -l) -ge $MAX_JOBS ]
do
# at least $MAX_JOBS are still running.
sleep 1
done
"$@" &
}
launch_when_not_busy bash job1.sh --args
launch_when_not_busy bash jobTwo.sh
launch_when_not_busy bash job_three.sh
...
wait
|
Let's say, I have 10 scripts that I want to run regularly as cron jobs. However, I don't want all of them to run at the same time. I want only 2 of them running simultaneously.One solution that I'm thinking of is create two script, put 5 statements on each of them, and them as separate entries in the crontab. However the solution seem very adhoc.Is there existing unix tool to perform the task I mentioned above?
|
Process Scheduling
|
You might want to take a look at theCookbook section on the Quartz site.There aretwo easy built-in methodsfor starting a Quartz Scheduler within a servlet environment, using either a<listener>or<servlet>in the app's web.xml.
|
I'm not really sure what is the best way to initialize Quartz to schedule a cron job.
My environment is Tomcat. I have one job that needs to be triggered every day.Should I create a separate Servlet to initialize Quartz and schedule my job?I'm thinking of creating a Servlet and on the init() schedule my job something like this:SchedulerFactory sf=new StdSchedulerFactory();
Scheduler sched=sf.getScheduler();
JobDetail jd=new JobDetail("job1","group1",CronJob.class);
CronTrigger ct=new CronTrigger("cronTrigger","group2","0 0/1 * * * ?");
sched.scheduleJob(jd,ct);
sched.start();I'm new to Quartz but I guess I always need to keep a reference to the SchedulerFactory in order for Quartz to be running, therefore having that on a Servlet will be best option?
|
What's the best way to initialize Quartz?
|
This is what I finally did: UseWhenever, because it integrates nicely with Capistrano and showed me how to run Rails code from within cron. My missing peace was basicallyscript/runner -e production 'ChangeObserver.recentchanges'which is now run every 5 minutes. Therecentchangesreads the last looked-at ID from a tmp-file, pulls all newChangerecords which have a higher ID than that and runs the normal observer code for each record (and saves the highest looked-at ID to the tmp-file, of course).
|
I'm integrating some non-rails-model tables in my Rails application. Everything works out very nicely, the way I set up the model is:class Change < ActiveRecord::Base
establish_connection(ActiveRecord::Base.configurations["otherdb_#{RAILS_ENV}"])
set_table_name "change"
endThis way I can use theChangemodel for all existing records withfindetc.Now I'd like to run some sort of notification, when a record is added to the table. Since the model never gets created viaChange.newandChange.saveusingActiveRecord::Observeris not an option.Is there any way I can get some of my Rails code to be executed, whenever a new record is added? I looked atdelayed_jobbut can't quite get my head around, how to set that up. I imagine it evolves around a cron-job, that selects all rows that where created since the job last ran and then calls the respective Rails code for each row.UpdateCurrently looking at Javan'sWhenever, looks like it can solve the 'run rails code from cron part'.
|
Monitor database table for external changes from within Rails application
|
It's possible. A quick google search foundthis example in perl. Here'sanother in bash. Also as a side note you should try to make sure your credentials are secured with permissions.Also take a look at these possible duplicates:question 1question 2question 3
|
Is it possible to use facebook php api and crontab to create status updates? Crontab would run the php code that sends the status update to facebook.The problem for me is the login part [$facebook->require_login();]. Crontab can't login, so can i send the login information (username and password) to facebook as well?my example code:$facebook = new Facebook($api_key, $secret);
$user = $facebook->require_login();
$output = "my status";
$result = $facebook->api_client->users_setStatus($output);
|
Facebook status update with PHP and Cron
|
By "user logs in", I suppose you mean "user would log in if he was using a browser" ?If yes, your PHP script that's crawling through HTML will need to :POST data like if it was filling in the formGet the answer from the server ; probably extract the session's cookiesSend those cookies for subsequent requestsYou might be interested in using some already-existing library to facilitate that.For instance, you can take a look atZend_Http_Client(see also; the part aboutSending Multiple Requests With the Same Clientwill probably interest you ;-) )You might also want to take a look at some other questions/answers, like :How would I go about writing a simple PHP bot?How to receive HTTP cookies from a web server in PHP?
|
I am currently running a php cronjob to crawl through some HTML. I have come to a scenario where I have to be logged in to access some data. How can this be achieved?The cronjob is running on a server which I dont have access to.Basically, let's just say, I am trying to access some HTML data which is only available after a user logs in. I have the login details but dont know how to implement it with the cronjob.Cheers!
|
Run cronjob as a logged in user
|
As you mentioned above all things are correct as per my past experience with the same situation.npm packagenode-crononly works fine if you have only one dyno
otherwise it will trigger based on a number of dynos.If you want to execute the cron perfectly without taking any risk (doesn't matter how much dyno's you have) I suggest you to use heroku add-on.
|
I'm building my app backend as a node/express API to be deployed on Heroku.I am new to implementing "cron jobs", and I found the npm library named node-cron which seems very straightforward.Is it as simple as just setting up the cron job in my app runtime code? I know it will not run when the heroku free dyno goes into "sleep mode" (based on other StackOverflow answers), but I plan to use paid dynos in production so that's not an issue.My main concern is when I "scale up" on heroku and run multiple dynos, will this cause weird interactions? Will every "instance" of my app on a separate dyno try to run its own crons independantly, causing duplication of work?I know heroku provides a free "scheduler" addon for this to spin up dynos to do this, but if the above won't happen, the scheduler heroku addon seems to be unneeded overhead in my case.Notes: my cron will be very simple, just doing some database clean up on old records, I didn't want to do it in the database layer to keep things simpler as it seems not super easy to schedule jobs in postgres.Any insights will be much appreciated. Thank you.
|
node cron jobs on heroku, is using the heroku scheduler necessary?
|
Assupport for specifying both a day-of-week AND a day-of-month parameter is not implemented,You can try with this:@Scheduled(cron = "0 5 0 ? * MON")
private void doTask(){
if(LocalDate.now().getDayOfMonth() != 1){
//your code here
}
}You can alsocheckandgeneratecorn for quartzhere.
|
I am usingquartz expressionsto create a trigger that should execute only on Mondays and theday of monthshould not be1.I already know that0 5 0 2-31 * MONexpression doesn't work becauseSpecifying both a day-of-week and a day-of-month parameter is not implemented. Is there any workaround for this issue? How can I achieve this?To summarize, if 1st day of month is Monday, the above expression should not be executed but for other Mondays of the month, it should be executed.
|
Cron expression to run only on Monday
|
You need to find outwhythe command is failing. The default output of a cron job is lost, unless you redirect it to a file and check it later.You can log it at the cron level (seehttp://www.thegeekstuff.com/2012/07/crontab-log/)59 23 * * * /home/john/bin/backup.sh >> /home/john/logs/backup.log 2>&1The2>&1folds stderr into the stdout, so both are saved.Or else you can log specific commands within your script:echo "Creating $NAME" >>/home/john/logs/backup.log
mysqldump -u root -pXXXX@2016 xxxx 2>>/home/john/logs/backup.log | gzip > /media/backup_folder/$NAMEOnce you have the error output, you should have important clues as to the cause of the failure.
|
i am running a cron job, that calls a sh script with the code bellow. I have noticed that sometimes it works, but sometimes i am getting a 0KB file. I have no idea what could be causing this 0KB or what could be done to fix this.DATE=`date +%Y-%m-%d-%H-%m`
NAME=bkp-server-207-$DATE.sql.gz
mysqldump -u root -pXXXX@2016 xxxx | gzip > /media/backup_folder/$NAME
|
mysqldump sometimes returns empty file
|
Try this (assuming that you're in Istanbul),CRON_TZvariable should be set before your cron entry :* * * * * rubHello.sh
0 19 * * * runKuku.sh
CRON_TZ="Europe/Rome"
17 13 * * * /tmp/job1.sh
CRON_TZ="Europe/Istanbul"
0 18 * * * /tmp/Job2.shOR* * * * * rubHello.sh
0 19 * * * runKuku.sh
0 18 * * * /tmp/Job2.sh
CRON_TZ="Europe/Rome"
17 13 * * * /tmp/job1.sh
|
I need to add a new task for crontab which will execute it in adifferentTZ than the local machine time.
I succeed to do it as you can see in the example below, but the problem is that from time i changed the TZ all the jobs after refers to the new TZ* * * * * rubHello.sh
0 19 * * * runKuku.sh
CRON_TZ="Europe/Rome"
17 13 * * * /tmp/job1.sh
0 18 * * * /tmp/Job2.shin the example above, job1 runs in Europe/Rome as my request, but also job2
runs in that time which is NOT OK.it there a way to tell crontab change the TZ for only specific task and get back to default crontab TZ for the next jobs after?Thank you.
|
How to set a different time zone for a SPECIFIC task in crontab?
|
It will execute at every hour, minute 0 (same as 60), second 0 (hh:00:00). So"cron="0 0 * * * ?", will also do.The/between values defines a range, so"cron="0 30/45 * * * ?"will execute when minute is 30 and then 15 times, until minute passes 45.If no cron job is executed at all, it seems scheduling is not started at all. Did you set the@EnableSchedulingannotation in your config?To test the availability, set it tocron = "* * * * * ?"(every second).
|
I am new to Spring. I am trying to run a cron job every hour and I am using the@Scheduled(cron="0 0/60 * * * ?")expression for this. So when does the job start? Lets say if i have deployed the application at 10:03 AM. Will the cron Job start at the next hour i.e., 11:00 AM or it starts at 10:03 AM first and then from the next consecutive hours like 11:00, 12:00 and so on..?Actually I deployed my application yesterday and I don't see the cron job running. I am trying to figure it out why it's not running. Meanwhile I just want to clarify myself.I have tried to follow the documentation, but I believe they didn't mention this in the documentation:https://docs.spring.io/spring/docs/current/spring-framework-reference/html/scheduling.html
|
When will the Spring Cron Job will be executed for the first time?
|
Because your google cloud instances can go down or up at any minute, (And also, you may have multiple instances of the same app running), which would make cron unreliable as it may trigger multiple times across multiple machines, google has created Task Scheduling, which is available on Google Compute Engine.A great tutorial can be foundhere, and a sample can be foundhere.For a PHP specific implementation of pub/sub, seethis link.
|
Due to the architecture of our App Engine application we can't use the App Engine cron service that Google provides and are looking for alternative options.One possible solution we have come up with is to allow our App Engine PHP application to automatically create a cronjob on a compute engine instance. This instance would simply be a utility machine which would handle nothing but the cron jobs.How would we create the crons in compute engine from within the App Engine application using PHP?
|
How to create a cron job on a Google Compute Engine instance via a PHP App Engine application?
|
I'd try this: First, modify your add or update to specify a job id:RecurringJob.AddOrUpdate("some-id", () => /* my method */, "*/20 * * * *");followed byRecurringJob.Trigger("some-id");To run a recurring job now, call the Trigger method.UPDATE: How about a delayed job then instead of a recurring job? Your "my method" creates a new delayed job at the end (Recursion), set to run after 20 mins. You will still use the Trigger method for the first run.
|
I have a number of tasks that i need run every 20 minutes. I can achieve this in Hangfire using the cron expressionRecurringJob.AddOrUpdate(() => /* my method */, "*/20 * * * *")The problem with this is, all my tasks will end up running at exactly the same time e.g. 00:00, 00:20, 00:40, 01:00Does anyone know of a way to stagger one's 20 minute interval tasks without implementing some sort of manual intervention?I'd just like Hangfire to run the jobs every 20 minutes from the time I create them, nothing too special :)
|
How to get Hangfire job scheduler to stagger my 20 minute interval jobs
|
If you are executing the same file and getting different output via shell and your browser, it's most likely you have different versions of PHP installed. Which is why you are gettingundefined function mysql_connect()because, you are referencingphp 5.5.0+to run your cronjob.The solution is to first check where php is installed.$ whereis phpThen try to check the versions usingphp -vand/usr/local/bin/php -vIf all is okay, and you havephp 5.5.0or above, you can simple removemysql_functions and use instead mysqli/PDO.At the end, your path should be like this.*/2 * * * * /usr/local/bin/php /path/to/cronjob.php
|
I want set up a cronjob for php script for every 2minutes in my ubuntu machine for this i have found the below link for reference but i am getting following error and i am not getting it how to resolve this error.Link for reference to set cronjobhttps://askubuntu.com/questions/177971/how-can-i-set-up-a-php-script-to-run-via-cronFirst error:
when i run a php script using command line i have got this error
Fatal error: Call to undefined function mysql_connect() in /opt/lampp/htdocs/ezypayzy/cronjob.php on line 2.But when i run this script on browser it is working fine.i dont know how to solve this.Command for php script:php /opt/lampp/htdocs/ezypayzy/cronjob.phpSecond error:
when i run a cronjob command on terminal it shows me this errorbash: */2: No such file or directoryCronjob command:*/2 * * * * /usr/local/bin/php/opt/lampp/htdocs/ezypayzy/cronjob.php
|
How to set cron job for php script in ubuntu
|
The most likely problem is the following statement in the cronJob declaration, '* * * * * *', this sends a request every second to the server and the server could get overwhelmed with too many requests than it can handle. Can you the declaration and check again?
|
While running the following code I can get only "Got error: connect ECONNREFUSED". Can any one suggest me, how to get the response from the below one and I am running this as a cron job, while this link is triggered I will get the response from the following.var http = require('http');
var CronJob = require('cron').CronJob;
new CronJob('* * * * * *', function() {
var url = 'http://localhost:3000/[email protected]&token=546546464547fdgdfgdfgdfg';
http.get(url, function(res) {
console.log("Got response: " + res.statusCode);
res.on("data", function(chunk) {
console.log("BODY: " + chunk);
});
}).on('error', function(e) {
console.log("Got error: " + e.message);
});
}, null, true, 'America/Los_Angeles');
|
Cron Job: Got error: connect ECONNREFUSED but not getting the response
|
The value of cron expression that was wrong (had 6 parts instead of 5) example: “H 22 ****”Once the expression was fixed, the cron expression was visible in the configuration and the job invoked according to the expression.
An easy way to check the expression is to try the edit the generated job manually, with the cron expression, and try to save it. If it is wrong Jenkins will not allow it.
|
I’m using Jenkins DSL plugin to generate a Job that needed to be invoked periodically
All was going as expected – only the triggering cron that was supposed to be generated by the code below was not displayed in the Job’s GUI, and the job is not triggered peridically
When I examined the actual generated job configuration file (config.xml) the cron text was thereHere is the code:dslFactory.freeStyleJob(jobName+'-PeriodicInvocation') {
triggers {
cron("$cronVal")
}
}The value of cronVal is fetched from a configuration file.Using DSL version 1.39, Jenkins version 1.625 on Ubuntu 12.04
|
Jenkins DSL plugin – cron triggering not generated
|
Define a cron job that runs every minute. Have it invoke a script that checks the current time, and executes your command only if the current time is a multiple of M.One way to do this is to get the result ofdate +%s(which is the number of seconds since the Epoch, 1970-01-01 00:00:00 GMT), divide by 60 to get minutes, and then compute the remainder modulo M. In bash:M=28
curr_second=$(date +%s)
curr_minute=$((curr_second / 60))
if (( curr_minute % M == 0)) ; then
# run your command
fi
|
I need to run a script file after every M minutes. This M is configurable. For now I have used the cron entry as below.*/M * * * * /tmp/test.shBut, by using above logic, M value is restricted to 5,10,15,30 etc., M can not be set to 28 for example. I can write a background service for doing this, but I wanted to know is there any alternative to cron job.
|
Alternative to cron job in linux for running a script after every M minutes?
|
So/remainderis doing the actual job right? Just call it inside callback.var request = require('request')
var CronJob = require('cron').CronJob;
new CronJob('* * * * * *', function() {
console.log('You will see this message every second');
request('http://www.google.com', function(error, response, body) {
if (!error && response.statusCode == 200) {
console.log('im ok')
// console.log(body) // Show the HTML for the Google homepage.
}
})
}, null, true, "America/Los_Angeles");
|
Hi i am a beginner in node js. I need to use the cron to mail the user about the pending payment. I am using the moduleCron. The url/remainderperforms all the neccessary function to do the job and is working perfectly fine. My doubt is can I call this url within the cron job. How can we use the request/response. When the cron is run, the output isnull.var CronJob = require('cron').CronJob;
new CronJob('00 * 23 * * *', function(req,res){
console.log(req);
}, null, true, "America/Los_Angeles");
|
How to use request/response with in node cron job
|
Single cron syntax is not possible. You can do last day of the month0 0 12 L 1/1 ? *.It will trigger last day of every month.0 0 12 29 1/1 ? *.If you trigger like this you will miss non leap year February.
|
Closed.This question does not meetStack Overflow guidelines. 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.Closed8 years ago.Improve this questionIs it possible to write a single cron expression which runs on the 29thday of every monthORthe last day if the month has only 28 days (e.g. February)?
|
How to run cron job on 29th of every month? [closed]
|
The error tells you that the shell could not locate thejavabinary to execute. This has nothing to do with theJAVA_HOMEenvironment variable, but with thePATHvariable which is consulted byshto find any command.When you run your task fromcron, the shell did not receive the same initialization as your interactive shell where the command works for you. You'll equally find thatJAVA_HOMEisn't set there, either.
|
I have scheduled my job to run every day at 12:30 with this command:30 12 * * * java -jar test.jarIt throws error:/bin/sh: 1: java: not foundI tried to run this command:java -jar test.jarfrom shell and it worked just fine.Now I don't understand. I would say it is happening becauseJAVA_HOMEenvironment variable is not set, but then why it works from shell?
|
Running jar with cron throws error: '/bin/sh: 1: java: not found'
|
Cron daemon is not started. You have to start it manually. Your output frompx -aef | grep cronshows thatgrepis running notcron.sudo cron start
|
I'm trying to run quick php update over cron tab on Cloud9 IDE.
Here is my crontab -l:*/2 * * * * php /home/ubuntu/workspace/public_html/updater.phpI also tried to use data from "whereis php" instead of simple php, but still nothing.
And here comes my question. Is there any time restriction eg. 1 hour minimum for cron in C9?
Or maybe I'm doing something wrong.
Tried to restart cron already.
|
Is there any time restriction for cloud9.ide?
|
Is this an issue with using " ' and `?Probably. Replacing `` with $() your command works:curl -o ~/location/filename.xml "http://url.asmx/do_this?&startDate=$(date -d '7 days ago' +\%Y-\%m-\%d)&endDate=$(date +\%Y-\%m-\%d)"
|
I am running a cron which includes a curl whch includes values for startDate and endDate which must be in the format yyyy-mm-dd. endDate is today and startDate is 7 days ago. Overall format is:curl -o ~/location/filename.xml "http://url.asmx/do_this?&startDate=x&endDate=y"Using a fixed start date this works running via terminal on macosx:&startDate=2014-10-01&endDate=`date +\%Y-\%m-\%d`"However, remembering that startDate should be 7 days prior to the system date, both of the methods below result in an error 'The specified Date was not in correct format. Dates should be in format: YYYY-MM-DD, such as 2011-12-24'startDate=`date -d '7 days ago' +\%Y-\%m-\%d`&endDate=`date +\%Y-\%m-\%d`
startDate=`date --date="7 days ago" +\%Y-\%m-\%d`&endDate=`date +\%Y-\%m-\%d`Is this an issue with using " ' and `?What am I doing wrong here? BTW I am trying to keep within a one line command line rather than use a script in a file.EDIT: From Googling and copying and pasting many suggestions, I have found that the following on a Mac forum that works:$(date -v-7d +%Y-%m-%d)However I've not come across -v before. I'm wondering what it is, is it Mac specific and will this present problems on other servers?
|
'7 days ago' date format issue in crontab
|
give a try with this:var rule = {hour: 00, minute: 01, dayOfWeek: 01, month: [0, 3, 6, 9]};
var logCost = schedule.scheduleJob(rule, function(){
console.log('logCost output this shit at: ' + dateFormat(Date(), 'isoTime'));
});Check here:https://github.com/mattpat/node-scheduleIt should be "dayOfWeek", and not "day".
|
I'm using a node module callednode-scheduleI have this function, it is expected to fire ONCE at the start of each quarter.var rule = {hour: 0, minute: 0, day: 1, month: [0, 3, 6, 9]};
var logCost = schedule.scheduleJob(rule, function(){
console.log('logCost output this shit at: ' + dateFormat(Date(), 'isoTime'));
});The problem is that the function just keeps executing during the whole day (the first day of the month that is). How do I re-write this to execute just ONCE, there is probably something wrong with my rule variable, but i dont see what.
|
Schedule jobs with Node-schedule
|
If it's a PHP script you want to run, in a CLI environment, I'd definitely usephp.If you want to run the PHP script in a server environment, use eitherwgetorcurl, but I'd argue that a process task like this should be executed on the CLI.
|
I have a question about what command to use to run a PHP script from Crontab.Which of these alternatives would be the most appropriate to use.* * * * * /usr/bin/php /var/www/project/cron.php
* * * * * /usr/bin/curl --silent --compressed http://localhost/project/cron.php
* * * * * /usr/bin/wget http://localhost/project/cron.phpI hope not to bother with my question. Thanks.
|
Crontab: PHP Wget or Curl
|
I think the simplest approach would probably be to have a single job which ran once an hour, which then went throughallthe offices, and found any that were now on a later day to the one when the job last ran. (You'd need to maintain that, of course, along with the office's time zone.) That would take care of the DST issue for you, and also cope with a situation when the scheduler went down for a while - the next time it came up, it would "catch up" for all the offices it had missed.
|
I need to run a CRON at midnight which auto-assigns some periodic tasks for the people working in my company. The situation I am facing is that my company basically has offices all around US, which has more than 1 timezone. So basically I would want the job to be done timezone-specific. Also, my server is running by UTC.If I set EDT as the base timezone (which is 4 hours behind UTC) and set the CRON to be triggered at midnight, the CRON time would be0 0 4 * * ?The possible way that I think can be is that instead of setting it just once, I set it to be triggered 7 times at the following times:0 0 4 * * ? [EDT]
0 0 5 * * ? [CDT]
0 0 6 * * ? [MDT]
0 0 7 * * ? [PDT]
0 0 8 * * ? [AKDT]
0 0 9 * * ? [HADT]
0 0 10 * * ? [HST]So once any of it triggers, it would check which of my offices come under this time zone and will do the job.This may work, as I believe, but does anyone else have any other option instead of this?
Also, I would need to fix for the Daylight saving, which I am not really sure about how I would want to do.
|
Setting multiple timezones in Java Scheduler Quartz Cron
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.