Response
stringlengths
8
2k
Instruction
stringlengths
18
2k
Prompt
stringlengths
14
160
Yes this is possible take a look at spring documentation:https://docs.spring.io/spring/docs/current/spring-framework-reference/html/scheduling.htmlYou can enableScheduling with the@EnableSchedulingAnnotation. Then you have to add the@Scheduled(cron="*/5 * * * * MON-FRI")Annotation to your function. Just start a Process in there which executes the Python script for you. Here is another link where it is explained how to start a python script from java in the console:How to execute Python script from Java?Hope that helps you.
I have a python script needs to be run periodically. At first, I could consider triggering this script via a cronjob task. However, in my case, I have to do this through spring. The solution I am thinking of is writing a scheduled task in my spring app, and then running the python script via command line call. Is this possible in spring?
triggering a python script in a spring scheduled task
Try with:@Scheduled(cron = "50 59/15 * * * *")Explanation:50 59/15 * * * * = at 50 seconds, every hour at 59 minute, every 15 minutes 50 59/15 * * * * = starting at 11:59:50 for every 15 minutes.Your issue is that*/Xmeans "every X". So0/14means every 14 minutes.More you can read in the docs:
I am usingSpring-Boot @Scheduled Cronfor caching data retrieved from persistent storage.I have two different tasks,Set result in cacheClear cacheTask1 will run for every 15 minutes. I have set cron like@Scheduled(cron = "0 0/15 * * * *")so the frequency would be12:00:0012:15:0012:30:00Now I want to run Task2 10 seconds before Task1ie11:59:5012:14:5012:29:50I am trying this expression@Scheduled(cron = "50 0/14 * * * *")But it fires for every 14 minutes interval.Can anyone please suggest me a solution to fix it?
Spring-Boot @Scheduled Cron expressions to make slight delay between two tasks?
using bash, you could always do:cd /root/crawler && python batchscript.pyit's always good policy to use absolute paths to programs/executables referenced in cron jobs.
This question already has answers here:python: Change the scripts working directory to the script's own directory [duplicate](5 answers)Closed7 years ago.I have a script that runs multiple instances of Python Scrapy crawlers, Crawlers are int/root/crawler/batchscript.pyand in/root/crawler/I have that scrapy crawler.Crawlers are working perfectly fine.batchscript.py looks like this, (posting only relevent code)from scrapy.settings import Settings from scrapy.utils.project import get_project_settings from amazon_crawler.spiders.amazon_scraper import MySpider process = CrawlerProcess(get_project_settings())When I runbatchscrip.pyinside/root/crawler/directory scraper runs fine.But when I run it from outside of this directory usingpython /root/crawler/batchscript.pythen it does not run as intended, (Settings are not imported correctly),get_project_settings()are empty.I have tried creating a BASH script tooI create bash script calledbatchinit.sh#!/bin/bash alias batchscript="cd /root/crawler/" python batchscript.pyand behaviour is same :(When I runbatchinit.shinside/root/crawler/directory scraper runs fine.But when I run it from outside of this directory usingbash /root/crawler/batchinit.shthen it does not run as intended, (Settings are not imported correctly),get_project_settings()are empty.Why I am doing it? What is ultimate goal?I want to create a cronjob for this script. I tried to schedule cronjobs using above mentioned commands but I have issues as mentioned above.
Cannot change directory to a script using bash - cron [duplicate]
In django you can setup cron usingdjango-chronographorchronograph.Django-chronograph is a simple application that allows you to control the frequency at which a Django management command gets run.Step 1: Create management command of your task in django. For creating django management command referWriting custom django-admin commands.Step 2: After creating django management command configure command in cronograph.Hope this helps you.
I still pretty new to the use of crontab in Django. I have followed the instruction in this linkhttps://hprog99.wordpress.com/2014/08/14/how-to-setup-django-cron-jobs/to help me set up my method, my_scheduled_job() in cron.py file, which I want to call every five minutes.Here is my updated setting.pyINSTALLED_APPS = ( 'django_crontab', ...) CRONJOBS = [ ('*/5 * * * *', 'myproject.cron.my_scheduled_job') ]After which I ran this:python manage.py crontab addOutput:adding cronjob: (d0428c9ae8227ed78b17bf32aca4bc67) -> ('*/5 * * * *', 'cinemas.cron.my_scheduled_job')Next: Nothing happens.How do I start this cron job locally? Is there a way to test if my job ran normally?
how to start Crontab in Django Project locally?
If you want manage your crontask withiout crotab from console you can use this Cron Task MAnagergithub.com/MUlt1mate/cron-managerSimple install with composer
How to add a cron job in a Silex PHP Server? I would like to do some tasks every midnights without a previous user request. I know we can use middleware functions in order to execute some tasks after and before a Request, but I would like to do without one of them.I just follow some samples which useConsoleServiceProvicebut, although code doesn't show any error, the execute method is never call. And, it is not a cron task.So, Is it possible to define a Cron job in Silex 1.x??Thanks.
Define Silex Cron job
You can not add exclusions to your cron job. You are much better off adding to your code the logic to not run on those days.var job = new CronJob({ cronTime: '00 30 11 * * 1-5', onTick: function() { var exclude = ['28-01-2017', '1-05-2017', '14-08-2016', '15-09-2016', '16-09-2016'] if (exclude.indexOf(convertDate()) > -1) { console.log('dont run'); } else { console.log('run'); } } }); job.start(); function convertDate() { var d = new Date(); return [pad(d.getDate()), pad(d.getMonth()+1), d.getFullYear()].join('-'); } function pad(s) { return (s < 10) ? '0' + s : s; }
I'm usingCron; anodejs packagefor cron job handling in NodeJs. Here's how I'm running a cron job:var job = new CronJob({ cronTime: '00 30 11 * * 1-5', onTick: function() { /* * Runs every weekday (Monday through Friday) * at 11:30:00 AM. It does not run on Saturday * or Sunday. */ } }); job.start();It's running flawlessly but is there anystandard wayto handle exception dates array handling? For example here's my dates array of national holidays and I don't want to run my cron job on these days:['28-01-2017', '1-05-2017', '14-08-2016', '15-09-2016', '16-09-2016']
Exception Dates Array handling in Nodejs Cron
If you have Python installed on your Raspberry Pi, then from the shell, you just need to run:# This installs pip (Python installer) as well as the requests library sudo apt-get install python-pipOnce that is installed, run:# To install the ImgurClient pip install imgurpythonThen you can just run your script at the shell by typing:python your_script_name.pyIf you do not already have Python installed, just run the following command to install it before the others:sudo apt-get install python
I have created a simple-medium complexity script written in Python using Pycharm on my laptop and I wish to run this on my Raspberry Pi using Crontab. All of my past programming experience has been with C++ and C# in Windows and so I would normally just do a build of the project and it all gets compiled and linked into a single executable file.For Python how do you "compile" the script so that it can be run on another PC? I use some external libraries (requests and ImgurClient) which I had to install using the Pycharm app. I guess I'm correct in thinking that these need to be taken across to the RaspPi too? My script is in two files and so do I need to copy both of these files across? Is there a way to build them into a single file to use easily?This is my first script which I've written just from my knowledge of other languages and a bit of Googling. Just don't know how to proceed now that I have the actual script.
"Compiling" Python to run on another machine
Check if your cron commands are OK by typing:$ crontab -lor right in/var/spool/cron/crontabYour command seems to be OK for a script that will be executed every day at 01AM.
I have set cron job command on my digital ocean server. 0 1 * * * php /var/www/html/domain/cron/index.php is it right coded?? Because its not running daily. Had check of 5mint and hourly, its working fine but not for each day. Please help me to find out the solution. Thanks in Advance.
How set cron job - PHP in digital ocean for daily bases?
I take it you have never heard of, or consideredMySQL Replication?The idea is that you do your backup & restore once, and then configure the replica to "subscribe" to a continuous stream of changes as they are made on the primary MySQL instance. Any change applied to the primary is applied automatically to the replica within seconds. You don't have to do the backup & restore procedure again, unless the replica gets damaged.It takes some care to set up and keep working, but it's a much more efficient method of keeping two instances in sync.@SusannahPotts mentions hot backup and/or incremental backup. You can get both of these features for free, without paying for MySQL Enterprise usingPercona XtraBackup.You can also consider usingMySQL Transportable Tablespaces.You'll need filesystem access to run either Percona XtraBackup or MySQL Enterprise Backup. It's not possible to use these physical backup tools for Amazon RDS, for example.One alternative is to create a replication slave in the same network as the live system, and run Percona XtraBackup on that slave, where you do have filesystem access.Another option is to stream the binary logs to another host (seehttps://dev.mysql.com/doc/refman/5.6/en/mysqlbinlog-backup.html) and then transfer them periodically to your local instance and replay them.Each of these solutions has pros and cons. It's hard to recommend which solution is best for you, because you aren't sharing full details about your requirements.
I maintain a server that runs daily cron jobs to aggregate data sources and generate reports, accessible by a private Ruby on Rails application.One of our data sources is a partial dump of one of our partner's databases. The partner runs an active application and the MySQL DB has hundreds of tables. They have given us read-only access to a relatively underpowered readonly slave of their application DB.Because of latency issues and performance bottlenecking on their slave DB, we have been maintaining a limited local copy of their DB. We only need about 20 tables for our reports, so I only dump those tables. We also only need the data to a daily granularity, so realtime sync is not a requirement.For a few months, I had implemented a nightly cron which streamed the dump of the necessary tables into a localproduction_tmpdatabase. Then, when all tables were imported, I droppedproductionand renamedproduction_tmptoproduction. This was working until the DB grew to over 25GB, and we started running into disk space limitations.For now, I have removed the redundancy step and am just streaming the dump straight intoproductionon our local server. This feels a bit flimsy to me, and I would like to implement a safer approach. Also, currently doing the full dump/load takes our server over 2 hours, and I'd like to implement an approach that doesn't take as long. The database will only keep growing, so I'd like to implement something future proof.Any suggestions would be appreciated!
What is an efficient way to maintain a local readonly copy of a live remote MySQL database?
You can add a cron for each extension thus:rm -f /home/username/public_html/subfolder/filesfolder/*.jpg rm -f /home/username/public_html/subfolder/filesfolder/*.png rm -f /home/username/public_html/subfolder/filesfolder/*.gif rm -f /home/username/public_html/subfolder/filesfolder/*.png
I have a cron job setup to run at a set interval to remove images from a folder. The problem I can’t solve is it removes my index. I need some help removing only file extensions such as .jpg, .png, .gif yet leaving my index.php file. The cron job I’m using now removes everything including my index.php allowing people to view the links in that folder. Can someone please tell me how to add extensions to delete while leaving my index or tell the cron job exclude my index file ? This is the cron I’m using.rm -f /home/username/public_html/subfolder/filesfolder/*
Deleting files from folder using cron job
From what I see, cron tries to access a file under "var/www/html/hello.php" which is relative, instead of "/var/www/html/hello.php" which is absolute.Check your path in your cron file ?
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed7 years ago.Improve this questionI have a php script hello.php which is used to send notification to my android device under /var/www/html and have a server on Amazon EC2. I am using putty and logged in via SSH.Ran crontab -eIn the first line of vi editor typed:* * * * * /bin/php /var/www/html/hello.phppressed esc and then :wq and crontab-l lists the job alsoEvery minute (since ***** is there) I get a mail which saysCould not open input file: var/www/html/hello.phpThe script is executing from the console, I triedchmod 755 /var/www/html/hello.phpPlease help with this
Cronjob added but not working [closed]
You usually need to add the SAS executable to the command. Assuming it is in the path then justsas /prod/file/sas-data2/....../SasProgram.sasshould work.If it is not in the path, then explicitly prefixsaswith the path.
I am new to the world of PuTTY and hoping this is an easy ask. I have 16 programs in SAS that I need to automatically kick off once a month using crontab via PuTTY environment. I have it set up to email me but it just tells me the file doesn't exist. What am I missing in my script?CRONTAB: SHELL=/bin/bash * 9 15 * * /prod/file/sas-data2/....../SasProgram.sasPlease help!
Running SAS program via Crontab PuTTY
Try setting the DISPLAY environment variable when running the scrot command:DISPLAY=:0 scrot ~/.hostlog/$folder/$(date +%H-%M-%S)
I am working on a script to take screenshot every 10 minutes usingscrotandcrontabfor repeating.My code isfolder=$(date +"%d-%m-%Y") mkdir -p ~/.hostlog/$folder sh ~/.hostlog/hostlog.sh >> ~/.hostlog/$folder/$(date +%H-%M-%S).txt & scrot ~/.hostlog/$folder/$(date +%H-%M-%S).jpg &When I run this script on terminal, I am able to get a screenshot. But when I add it tocrontab. I do not get any screenshot. But I get the text file for this.sh ~/.hostlog/hostlog.sh >> ~/.hostlog/$folder/$(date +%H-%M-%S).txt &I did not get the output for this.scrot ~/.hostlog/$folder/$(date +%H-%M-%S).jpg &What is wrong here?
Scrot screenshot shell script not working inside crontab
What you're looking for is an Escalation. Escalations are instances of a special Cron Task that has been designed to use a query (a target object and a where clause) to find records and then to apply actions to and / or send emails from each record found.You'll need to define the where clause against MAXUSER to locate the records you want to deactivate and find or define an Action to change the status of the records found. You can then hook the query and the action together via an Escalation.
I am very new to maximo. I wanted to know how to inactivate users who are not using maximo anymore. I tried googling this but I am not able to find enough material on Maximo. I have to write a cron task to do that. I saw this:http://www.ibm.com/support/knowledgecenter/SSZRHJ/com.ibm.mbs.doc/autoscript/t_cron_task_scripts.htmlCan anyone give e a few pointers on how to write it, maybe a sample cron task?
How to inactivate Users in maximo who don't use it anymore?
From what I see on their site all they do is visit a URL that you provide.So, you'll have to create a URL which executes that javascript code you want.With the help ofnodejsyou can execute javascript on server-side
I have a JS that I want to run with a frequency.I have registered on the page cron-job.org. Thanks for making the page free! But: there is no user manual, so I am a bit stuck...I´m able to run php-scripts from cron-job.org, but haven´t succeeded in running JS. Any ideas on how to do this on cron-job.org or any tips of a free cron-service with JS-support?
Running JS from cron-job.org
After plenty of searching and trial and error the issue related to the "system user" SSH settings for the domain.I managed to created the task successfully in the root users cron ("system wide"). This worked so after plenty of digging had to set SSH access for the user the cron jobs were being run under - assumed already had accessOnce set the files and folders became accessible and the cron jobs now run successfully - phew!Thanks for your help ROn Brouwers
I am trying to run an artisan command from a cron task but I keep getting errors.In Plesk I have created this task:php /var/www/vhosts/domainxxx.co.uk/httpdocs/artisan schedule:runI'm trying to run a queueHowever I get an errorCould not open input file: php /var/www/vhosts/domainxxx.co.uk/httpdocs/artisan schedule:runif I run the commandphp artisan schedule:runfrom the httpdocs directory it works.I've tried loads of combinations of the path and full path to php but nothing seems to work.What am I doing wrong?Fiddling about I created a test script in the httpdocs calledcrontest.phpwhich just echoed out a status. I'm able to get this running with cron using this command:/usr/bin/php /var/www/vhosts/domainxxx.co.uk/httpdocs/crontest.phpThe log I get shows as the domain user rather than the root user - don't know if this makes a difference? I can see the test output in the notification I receive.Switching this to:/usr/bin/php /var/www/vhosts/domainxxx.co.uk/httpdocs/artisan schedule:run 1I get the error:/usr/bin/php: No such file or directoryConfused - does this error relate to php or artisan (assume artisan as it works for the tst script). Can anyone help please. Artisan is definately there :(
Unable to run artisan command via cron [laravel 5.2]
Please have a look atScheduler.The Scheduler is designed to be the central place to manage all kind of tasks that need to be executed on a regular basis, without needing someone to actually press a button.If no existing task fits your needs, you cancreate an own task.
Is it possible to force Typo3 to refresh websites by an external trigger (e.g. web server cron job or manual trigger)? Could you please describe some best practices?
Refresh Typo3 by web server cron job
You are looking at the crontabs of 2 different users. Looks like your VNC sessions and SSH session are using different user to access the same machine. Trysudo crontab -l -u <username>to list the crontab of a usersudo crontab -l -u root sudo crontab -l -u ubuntu
I installed ubuntu desktop on my Amazon EC2 instance usingapt-get install ubuntu-desktopand did the rest of the setup.I logged using TighVNC viewer.To my surprise, when I docrontab -eon my desktop terminal it's a different file than when I docrontab -eon my SSH (using Putty).
Different Crontabs?
Cron doesn't have functionality to run a job every 40 minutes. In fact*/40 * * * *will run the job on 40th minute of every hour, and then at the end of 59th minute of every hour and so on. So intervals between the job will be 40 mins, and then 20 mins, and so forth. The reason is that 60 is not dividable by 40.40 * * * *will just run the job on 40th minute of every hour (once an hour).*/30 * * * *on the other hand will indeed run the job every 30 minutes, because 60 mod 30 = 0If you truly want to run every job EVERY 40 minutes, you might need to use some more advanced scheduler, such asfcron(http://fcron.free.fr/). That scheduler truly supports that and some other cool features.Answering the question about triggering the job immediately, then I would suggest just programming the job on the very next minute, and inside you script maintaining a counter, and allow the script to run only once. After is script is executed, it can intelligently remove itself from the cron.
I have a requirement wherein i a m writing a utility which requires the cron trigger to fire immediately and then after a regular interval of 30 or 40 minutes. Right now my expression is like this 0 0/40 * * * ? but it starts the trigger after 40 minutes of start of application. What should be the expression or a programmatic way to implement the above scenario in java.
cron trigger that starts immediately and then runs after time interval
In basic scenarios the MySQL connections will be closed when the mysql client within the bash script finishes running.If you are running the mysql command line Linux client within your bash script then bash would normally wait for the mysql process to exit before continuing to the end of the script.There are ways to persist processes beyond the life of the bash script but you haven't mentioned using those in your question.If you are using a mysql library that has a close function - most of the MySQL libraries have this in the api then you should use it. Although the default process behaviour will probably clean up open connections for you, it helps to get in the habit of closing resources that you are not going to require again within your code as this makes it more scalable and also informs other developers of your intended behaviour.
When I run report jobs (get net sales data from mysql) in crontab (bashscript) , I establish a connection to mysql and get the required data.Does this leave mysql connections open or all the connections are closed on job completion?UPDATE - I use bash script to connect to mysql.
Does crontab leave mysql connections open?
I encountered the same problem today, the post is old but people may end up here so:The problem is crontab runs from the root directory so relative paths start from the root (/) and get a null point exception. On cronjob you can precede your command withcd $jar.directoryAssume you have your jar file in /home/project/data and want yo run every night:> crontab -e > 0 0 * * * cd /home/project/data && /usr/bin/java -jar program.jar >> log.txt 2>&1
In my java program, I am trying to save a.csvfile into mydatafolder located in the same folder as the mainjarfile.Previously, when I used to run my programs on Windows machines, my relative path was:data\\foo.csv. When I tried the same on Linux, it created and saved the file with name:data\\foo.csvin the root directory.Then I tried to set the path todata/foo.csvand I am getting this error:java.io.FileNotFoundException: data/04-12-2015.csv (No such file or directory) at java.io.FileOutputStream.open(Native Method) at java.io.FileOutputStream.<init>(Unknown Source) at java.io.FileOutputStream.<init>(Unknown Source) at java.io.FileWriter.<init>(Unknown Source) at main.Main.saveResultsToFile(Main.java:121) at main.Main.main(Main.java:92)I have set permissions of the directory to 777 (granted all permissions to everyone).Code responsible for creating and saving the file:String fileName = "data/foo.csv" BufferedWriter bw = new BufferedWriter(new FileWriter(fileName));Edit:The permission is not recursive, if that changes anything. Only thedatafolder has 777 permission.
Java console app running as a cron job having issue with relative path
Yes. This could definitely cause issues. You havea race condition. If you wish, you could acquire a lock somehow on acritical sectionwhich would prevent the next invocation from entering a section of code until the first invocation of the command finished. You may be able to do a row lock or a table lock for the underlying data.Let's presume you're using MySQL which has specific lock syntax (DB dependent) and you have this model:class Email(models.Model): sent = models.BooleanField(default=False) subj = models.CharField(max_length=140) msg = models.TextField()You can create a lock object like this:from django.db import connection [...] class EmailLocks(object): def __init__(self): self.c = connection.cursor() def __enter__(self): self.c.execute('''lock tables my_app_email write''') def __exit__(self, *err): self.c.execute('unlock tables')Then lockallof your critical sections like:with EmailLocks(): # read the email table and decide if you need to process it for e in Email.objects.filter(sent=False): # send the email # mark the email as sent e.sent = True e.save()The lock object will automatically unlock the table on exit. Also, if you throw an exception in your code, the table will still be unlocked.
I have a recurring cron job that runs a Django management command. The command interacts with the ORM, sends email with sendmail, and sends SMS with Twilio. It's possible that the cron jobs will begin to overlap. In other words, the job (that runs this command) might still be executing when the next job starts to run. Will this cause any issues? (I don't want to wait for the management command to finish executing before running the management command again with cron).EDIT:The very beginning of the management command gets a timestamp of when the command was run. At a minimum, this timestamp needs to be accurate. It would be nice if the rest of the command didn't wait for the previous cron job to finish running, but that's non-critical.EDIT 2:The cron job only reads from the DB, it doesn't write to it. The application has to continue to work while the cron job is running. The application reads and writes from the DB.
Overlapping cron job that runs the same Django management command: problematic?
1 * * 1,4 /home/abc/xyz.ksh >/dev/null 2>&1Where 1 and 4 translates to Monday and Thursday respectively. Valid range is 0 to 6 with 0 being Sunday and 6 representing Saturday
I want schedule the cron job on every Monday and Thursday at 1.00 AM. I have used below command but I am getting an error.0 1 * * Mon,Thu /home/abc/xyz.kshcrontab: error on previous line; unexpected character found in line. crontab: errors detected in input, no crontab file generated.Can anyone advise me how to set it up?
Error while setting up cron job?
The application is trying to connect to the MySQL database without a user (anonymous). Did you check if the MySQL instance allows anonymous access? Just runmysql. If you get the same response, than that is your problem.Posible solutions:configure your application with a mysql username/password.https://codex.wordpress.org/Installing_WordPressconfigure mysql for anonymous access (not recommended). This is the default, so someone must have set it up with a user.How are you running mysqld?
I'm running a cron job in my WordPress site and getting these two errorsWarning: mysql_query(): A link to the server could not be established in/home/geekda6/public_html/wp-content/plugins/maxblogpress-ninja-affiliate/ninja-affiliate-library/include/mbp-ninja-affiliate.cls.phpon line251Warning: mysql_query(): Access denied for user ''@'localhost' (using password: NO) in/home/geekda6/public_html/wp-content/plugins/maxblogpress-ninja-affiliate/ninja-affiliate-library/include/mbp-ninja-affiliate.cls.phpon line267Invalid query: 1045: Access denied for user ''@'localhost' (using password: NO)Here is my file.https://gist.github.com/amarilindra/d89a0e2b90615e0f0c28
mysql_query(): Access denied for user ''@'localhost' (using password: NO)
I gave an answer to a similar questionhere - Best way to schedule code execution. Basically have a cron job run at a certain frequency to check datastore to see if there is anything to run at that time. You can restrict user input to 15 minute increments and have the cron job check every 15 minutes or at whatever rate you need.
I have an app running on GAE cloud (Java web application). I have gone through the documentation that shows how to create the cron jobs (using cron.xml that we place in WEB-INF). However the frequency is also set in the same config file along with time/date.If I need to run a job (or more than one job) based on the User input how do I achieve that? For example, if there is a text box on the web app jsp that allows the User to input 11:30 am, how do I run a specific job at that time? Thanks.
Google App Engine - Run job based on user input time
Incorrect:* * * * * php /usr/local/php5/bin/php5 /path/to/file/ ^^^--php executable ^^^^^^^^^^^^^^^^^^^^^^^^---script to runYou're telling php to run itself. The cron line should be simply:* * * * * executable argumentse.g.* * * * * /usr/bin/php /path/to/script.php
Ok, I have been trying to work this cron job for a whole day and no advancement on that part. I have put in several code into Terminal(MAC) what everyone says on this website, but none of them work. The code which I have seen the most is:* * * * * php /usr/local/php5/bin/php5 /path/to/file/or others something along those lines. However, none of them work.Is there something wrong with the code? If so, please point it out.If there isn't, I am done with cron job. I have found another php script which one can write to insert data into MYSQL table every second, but I don't think this one works either.<?php $start = microtime(true); set_time_limit(60); for ($i = 0; $i < 59; ++$i) { doMyThings(); time_sleep_until($start + $i + 1); } ?>Is this code right? Is there any other methods I could use (written in php script like above) which you know about?
Cron job not working properly; What is wrong or other methods?
Have you looked at python's standardloggingmodule? It has handlers for logging to files (which you can then look at independently of the cronjob). It can also take custom handlers.
I have a python script that I'm setting up as a cron job and since cron jobs don't have a terminal to write standard output to I was wondering if there was a simple way to log the entirety of standard output in a text file. Basically, put everything that would be printed in the terminal if I ran this script myself in a text file that gets appended every time the cron job runs.
Python cron job logging
ssh --helpsays that there is a-F configfileoption. However, I thinksshshould still be checking in ~/.ssh/config and/etc/ssh/ssh_config, even when run viacron.When run fromcron, theHOMEenvironment variable is set to point to your normal home directory, sosshhas all the information it needs to locate the standard configuration files.I tested this by putting the followingcronjob in place:* * * * * strace -o /tmp/trace -f -s 80 ssh localhost uptime > /tmp/traceAnd inspecting/tmp/traceafter the job has run, I see:29079 open("/home/lars/.ssh/config", O_RDONLY) = 3 29079 open("/etc/ssh/ssh_config", O_RDONLY) = 3UpdateOn my OS X machine (OS X 10.10.3), I set up the following~/.ssh/configfile:Host stackoverflow Hostname fileserver.house IdentityFile fileserver_rsaI created the following cron entry:* * * * * ssh stackoverflow uptime > $HOME/outputThe only way that would work would be if ssh were reading my~/.ssh/configfile...and it works just fine. What leads you do believe that things aren't working?
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 questionssh_configfiles allow you to configure an ssh clientYou can specify aliases, default users and identity files for different ssh hosts, amongst other thingsThe docs state that the ssh_config options are loaded magically by the ssh client in the following order:command line optionsuser-specific file (~/.ssh/config)system-wide file (/etc/ssh/ssh_config)However, these configuration options aren't automatically available/respected within a cron job contexthow can you load an ssh configfile such as ~/.ssh/config for a crontab context or in a specific cronjob?Update: issue was this:https://superuser.com/questions/508408/public-key-always-asking-for-password-and-keyphrase
how do you load an ssh_config file within a cron job [closed]
For the path to the database, your code uses a relative path that assumes the current directory is the directory in which the script resides. It is not.Instead of"../database.sqlite"useuse FindBin qw( $RealBin ); "$RealBin/../database.sqlite"oruse FindBin qw( $RealBin ); chdir($RealBin); "../database.sqlite"
I have a script that I run manually every hour in my Laravel that's under this path:/var/www/name/storage/scripts/getListOfClassesFromSubjects.plWhat I normally do is, I cd to/scripts/, and I manually run:./getListOfClassesFromSubjects.plAnd the script works fine.Today, I setup a crontab to automate this (obviously).0,30 * * * * /var/www/name/storage/scripts/getListOfClassesFromSubjects.pl >> /var/www/name/storage/logs/schedulizer.log 2>&1Within my logs are this:DBD::SQLite::db prepare failed: no such table: subject_urls at /var/www/loop/storage/scripts/getListOfClassesFromSubjects.pl line 56.Which is an anomaly because when I run the script manually, it's fine.This is my database's permissions:-rw-r--r-- 1 root root 11750400 Aug 4 12:30 database.sqliteSo I'm thinking this is the issue with the rwx permissions, so I changed the DB to 755:-rwxr-xr-x 1 root root 11750400 Aug 4 12:30 database.sqliteStill the same issue
Script running in crontab reporting database missing error when manually running it doesn't cause the issue
I opted for another solution, just analysed the size of cache at which site crashes and scheduled a cron to flush. Its working fine.
Problem:Webpage loading fails sometimes randomly, sometime partial(no css, no image just raw html, both admin and frontend).**Temporary Solution we had is to ** delete/flush cache, its a magento website, and it works.What I'm trying to dois to schedule a cron job, which will check the page loading, it will be checking css/images loading. if it findsproblemit will flush cache and email or make a log entry.Can you guide me how I can detect by running a server side script.Thank you all
need to schedule a cron php to check webpage loading
Since the format of crontab is like this:+---------------- minute (0 - 59) | +------------- hour (0 - 23) | | +---------- day of month (1 - 31) | | | +------- month (1 - 12) | | | | +---- day of week (0 - 6) (Sunday=0 or 7) | | | | | * * * * * command to be executedTo execute it every week on Sunday irrespective of the month you need to write it like this:0 2 * * 7 sh /home/user/folder/myscript.sh week > /home/user/.crontablog/crontab.log
Three days ago I installed the following crontab job with crontab -e:# execute weekly 0 2 2-31 * 7 sh /home/user/folder/myscript.sh week > /home/user/.crontablog/crontab.logIt's supposed to be executed every sunday night at 2am except the 1st of the month. However it's executed every night at 2am. What's my mistake? I tried 0 instead of 7 for Sunday with the same result :/Thank you.
Crontab job executed every day instead every month
You can useffmpegwithout worrying too much about the protocols and formats since it has an auto-detection feature.ffmpeg -i "http://live.leanstream.co/CKBTFM?type=.flv&playertype=socast1" -t 3600 -f flv out.flvwhere-t 3600is the 1 hour time limit.If you only need to fetch information about the stream you can useffprobe.https://www.ffmpeg.org/
I am trying to setup a cronjob that will run everyday at a specific time and record an .flv audio stream for an hour and then save the file and quit recording.I know of a lot of rtmp tools to download such things, but I am unsure if the stream actually is rtmp as using the rtmp protocol in players such as VLC do not work.In VLC I can play:http://live.leanstream.co/CKBTFM?type=.flv&playertype=socast1I however cannot play:rtmp://live.leanstream.co/CKBTFM?type=.flv&playertype=socast1How do I discover what kind of protocol is being used for this stream so that I can find the correct tool.Edit: It looks like I can actually change the URL so that it gives me a different format such as.mp3:http://live.leanstream.co/CKBTFM?type=.mp3When trying to use tools such as Streamripper or wget I am receiving 404 errors which doesn't make sense as I can listen to the streams from my browser and vlc:$ wget -O stream.mp3 "http://live.leanstream.co/CKBTFM?type=.mp3" --2015-06-24 13:58:23-- http://live.leanstream.co/CKBTFM?type=.mp3 Resolving live.leanstream.co (live.leanstream.co)... 199.168.112.72 Connecting to live.leanstream.co (live.leanstream.co)|199.168.112.72|:80... connected. HTTP request sent, awaiting response... 404 Not Available 2015-06-24 13:58:24 ERROR 404: Not Available.
Downloading a .flv stream
You can force a particular shell withSHELL=bash */5 * etc...or whatever in the crontab. Then make sure wget is available in that shell's path.Otherwise just give an absolute /usr/bin/wget path instead.*/5 * * * * /usr/bin/wget etc...
I am pretty new to setting up cron jobs. What I've done so far is set one up to run every 5 minutes using the following script:*/5 * * * * wget -q localhost:8888/example/index.php/controller/functionWhen I run just the wget part from the command line, it works perfectly. But in the crontab, while the logs show it being ran every 5 minutes, nothing is happening. Am I missing something easy? Any help is appreciated!Thanks!
Cron job with CodeIgniter using wget
Generate the invoices the moment they are saved in the database and store the filesystem-URL with the database entry. If the user requests a package of invoices of a certain time period, collect the already generated PDFs into a zip-file and provide a download link. Requirement is enough space for file storage on the server.You can limit the invoice storing to one year. If an user requests older invoices they must be generated otf.Follow-Up Answer: Since you are in PHP-environment, i would suggest implementing some kind of invoiceChanged handler. If you call it (with parameter invoiceNr), the deprecated PDF-file gets deleted and a new one is generated according to the modified data. If it uses the same file-name, you do not even have to update the file-URL in your database.
I need to give our users the ability to export a bunch of their PDF's (invoices).The problem is, the PDF's are generated everytime a user opens them.So I don't have them already stored in a filesystem.So, my question is, what would be an efficient way of exporting a user's PDF's, when they want to?For example, a user wants to export 100 invoices from the previous quarter.I would then need to call a script that generates the PDF's and put them in a .zip file.But, what if multiple users request a heavy export at the same time?I was thinking of running a cronjob every 10 minutes or so, but that doesn't solve the possible heavyness of the script.Do I need to run multiple cronjobs, so they can each handle a portion of the exports?Or can I somehow create a really efficient script, and maybe separate all PDF's in several batches?I'm usingwkhtmltopdfto generate the PDF's.So fortunately, it's pretty fast to render the PDF's.Although it still depends on the content, of course.On average, a single PDF takes about 3-5 seconds to render.Any help or guidelines would be greatly appreciated!ThanksFollow-up question: If I save every invoice into a filesystem, as soon as it's created or updated, I need to find a way to do this in the background, to avoid unnecessary waiting.Queues would be my savior, right?
Efficient way of exporting a bunch of PDF's from a user?
It looks like the close isn't working correctly when run through cron, but it works fine when called manually.Sounds to me like yarn is expecting some environment variables to be set which aren't set when run as a cron job. Try the following to debug this:* * * * * yarn application -list > /home/me/error_log 2>&1Now wait 1 minute and look into/home/me/error_logand see what it's complaining about. This will give you a hint on what you need to do to fix your environment.
I have a script called yarn_monitor.py. When I run it, the program executes correctly and when I look at the running processes usingps -u myname, everything is clear.But when I run yarn_monitor.py using cron:* * * * * /home/me/projects/yarn_monitor/yarn_monitor.pyI see several processes that don't quit. Here they are repeated twice:19337 ? 00:00:00 yarn_monitor.py 19338 ? 00:00:03 java 19418 ? 00:00:00 sendmail 19419 ? 00:00:00 postdrop 20043 ? 00:00:00 yarn_monitor.py 20046 ? 00:00:02 java 20199 ? 00:00:00 sendmail 20200 ? 00:00:00 postdropEventually, as I let cron keep running the job, I get a Java GC out of memory error.As far as I know I'm not using any Java in my process. Here are my imports:from __future__ import print_function import os import sys import re import time from pysnmp.entity.rfc3413.oneliner import ntforg from pysnmp.proto import rfc1902Any idea what could be happening? Or ways to keep running this job while killing previously created processes?
Processes don't terminate when I call Python script using crontab
You should not provide a full path when trying to execute a class with "java". The "java" command expects to receive just the class name as an argument.That's why this works properly:java HelloWorldBut this does not:/usr/bin/java /home/shivajividhale/cloudOccular/HelloWorldTo make the latter work, you need to provide just the class name, and additionally a "classpath" so that Java knows where to find that class. You can use the "-cp" option to provide the classpath.Try this:/usr/bin/java -cp /home/shivajividhale/cloudOccular/ HelloWorld
I'm trying to run a simple java helloworld program with crontab. I made the following java code: helloworld.java:class HelloWorld { public static void main (String args[]) { System.out.println("Hello world"); } }I then try to run this from a crontab in the following sequence:crontab -eAt the end i insert this line0,7,10,15,30,46,50,55,59 * * * * root /usr/bin/java /home/shivajividhale/cloudOccular/HelloWorld >/dev/null 2>&1However, I am not able to see the helloworld putput in the syslog. Is everything correct? How do I check if the class file is being executed or not. I tried printing the output to a text file with the time on it as well. But nothing is being done on the file.Running the file normallyjava HelloWorldyields proper output. I also made sure the crontab ends with a new line.I just want to get started with having a class file run by the crontab. Oher posts discuss about crontab running bash scripts, I just want to run just this simple program. I just want to print out Hello World along with the time to ensure program execution at the defined intervals. Any help?
Run simple Java class file with crontab
The PATH variable in cron is not the one you get when logging in. Simple enough: cron does not log you (nor any other user) in.Similarly, you have a current directory when logging in that's not all that likely to be the same that's going to get used by root's cron jobs.Simplest and most robust solution is to add full paths in front of all commands such as php, unzip, wget ... AND to cd to the directory you need to be in.To find out which path you use when you're executing commands while logged in, use "which":So e.g.:$ which php /weird/place/phpWould mean you replace the linephp test.php /tmp/stat/top-1m.csvwith/weird/place/php test.php /tmp/stat/top-1m.csvand similarly, add the location to the script test.php just as well. so you end up with something like/weird/place/php /home/user/subdir/test.php /tmp/stat/top-1m.csvNormally a unix system is setup to email the output of cronjobs to the user who owns the crontab. Might be root in your case from the looks of it. Check that email and try to get it delivered to you so you can see these errors and react to them as needed.
I have a usr/local/bin/test.sh file:#!/bin/bash rm -f /tmp/stat/top-1m.csv.zip wget -P /tmp/stat/ http://s3.amazonaws.com/alexa-static/top-1m.csv.zip rm -f /tmp/stat/top-1m.csv unzip -d /tmp/stat/ /tmp/stat/top-1m.csv.zip php test.php /tmp/stat/top-1m.csvI'm trying to run it on a server, using crontab. Code in/etc/crontab:SHELL=/bin/bash PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin:/tmp/stat MAILTO=root HOME=/ 25 12 * * * root /usr/local/bin/test.sh.zipped file gets downloaded and unzipped (very slowly, but it gets done). My test.php file is supposed to collect data from the file and insert it into a mysql database. test. If I execute test.sh in the terminal, everything is fine. But nothing gets written in the database through cron job. Why is this? I don't even know if it starts ezecuting test.php at all.Help?
Execute php in crontab
You should use multiple cron expressions instead of just one. Try this:0 30-59 8 ? * MON-WED,SAT,SUN * // 8:30 - 8:59 0 * 9-11 ? * MON-WED,SAT,SUN * // 9:00 - 11:59 0 0-30 12 ? * MON-WED,SAT,SUN * // 12:00 - 12:30Please note that Year field isn't mandatory, so you can omit the last field, like this:0 30-59 8 ? * MON-WED,SAT,SUN // 8:30 - 8:59 0 * 9-11 ? * MON-WED,SAT,SUN // 9:00 - 11:59 0 0-30 12 ? * MON-WED,SAT,SUN // 12:00 - 12:30Good luck!
I want to create cron that run from 8:30 to 12:30 every one minute in MON,TUE,WED,SAT,SUN.I create this expression:0 30/1 8-12 ? * MON,TUE,WED,THU,SUN *But not work for me.
Create cron Expression from 8:30 to 12:30
Whatever the task may be specifically, you would probably be best off implementing it in the python script. This seems more straight-forward. For instance:while True: try: # your task # check if it was successful and if so break except Exception: # a relevant exception would be best pass # you could even use sleep() here(time module) # to wait a few seconds between tries
In my mind this is an easy task, but i don't know how to realize it.I have got a python script, that is likely to crash on the first few tries. (It is calling a websocket, that is not yet ready.)Can i tell cronjob to keep on trying to run this script until it finally works? Or do i have to implement this in the python script itself?This is the line in Crontab@reboot sh /home/pi/launcher.shAnd this is the .sh-file.#!/bin/sh # launcher.sh cd / sudo python /home/pi/example.py cd /
How to successful launch a python cronjob?
22 * * * curl http://myserver.com/test/test.phpCron would be start every day at 10:30pm
I am trying to run a particular PHP script using CRON and PuTTy on everyday at 10.30pm. I have managed to run this script in every 5 minutes by this following statement*/5 * * * * curl http://myserver.com/test/test.phpThis script enables me to run test.php on every 5 minutes but I want it to run everyday 10.30 pm. Can anyone please help me with this situation. This is first time am working with CRON JOB.
Scheduling a cron job for a particular time
The issue was due to the file being requested not being a literal location. This is the code which did not work:$filename = "amazon_data.txt"; $file = fopen($filename, "a+") or die("Unable to open $filename!\n");This may work fine when the script is run remotely via HTTP, but it may cause issues when running cron jobs or execution in the terminal. Changing the$filenameto be the full location fixed this issue.$filename = dirname(__FILE__)."/"."amazon_data.txt"; $file = fopen($filename, "a+") or die("Unable to open $filename!\n");Why does this happen? I am guessing instead of the php file's folder being used, it was using a directory which the apache user did not have access to, such as the current working directory that the command in terminal was being executed from.
I am attempting to create a cronjob under the user apache, but I get permission denied errors for files that are accessed by the program. The specific file that my php script cannot access is /var/www/html/amazon/amazon_data.txt. Here is me checking the permissions, and testing to see if I can write to the file:bash-3.2$ whoami apache bash-3.2$ ls -l /var/www/html/amazon/amazon_data.txt -rwxrwxr-- 1 apache apache 1082 Apr 3 15:43 /var/www/html/amazon/amazon_data.txt bash-3.2$ vi /var/www/html/amazon/amazon_data.txtNow I try to run a script that tries to access the file I get this warning:bash-3.2$ /usr/bin/php /var/www/html/amazon/amazon_inventory_sync.php PHP Warning: Module 'json' already loaded in Unknown on line 0 PHP Warning: fopen(amazon_data.txt): failed to open stream: Permission denied in /var/www/html/amazon/amazon_inventory_sync.php on line 26 Warning: fopen(amazon_data.txt): failed to open stream: Permission denied in /var/www/html/amazon/amazon_inventory_sync.php on line 26 Unable to open amazon_data.txt!bash-3.2$Why can I access and edit the file with the user just fine, but not in the php script when executing it via command line? There is no issue when I run the script from a browser.Edit: I can run it fine under the user soh, who is in the group apache. apache is also in the group apache.
Permission denied when executing php from command line, and crontab
You are better off using the--setup-onlyoption to mod_wsgi-express or the Django integration for it, to generate the configuration but not run it. Then as others have mentioned, integrate it into the system service manager.The two commands for starting and stopping the Apache/mod_wsgi instance would beapachectl startandapachectl stop, whereapachectlis that which was generated when running with the additional--setup-onlyoption.When running it as a system service, also make sure you use the--server-rootoption to specify a more persistent location for the generated configuration. Do not use the default under/tmpif running for anything but temporary development sessions as some Linux systems will remove files under/tmpcausing things to start failing after a while.Also, since under a service manager it would generally be starting as root, particularly if listening on port 80 is a requirement, ensure you use the--userand--groupoptions to specify what user/group your Python web application should run as.Read:https://pypi.python.org/pypi/mod_wsgifor more details of the--setup-onlyoption andstart-servercommands for generating the configuration. Because you are using the Django integration, you will need to use the--setup-onlyoption.For more informed helped, bring your issue to the mod_wsgi mailing list. The mod_wsgi-express way of running Apache/mod_wsgi is new enough that unlikely that anyone here is really going to know much about it.
my group and I are running a server that is based upon Django and uses mod_wsgi to run an Apache server. We will not be working on this project after it is over, so I am attempting to set up cronjob similar functionality to check if the apache server has shut down(system restart or power failure), and if it has, will restart the server for me. I've found documentation on how to check if an apache server is down and restart the server if it is, but our server uses https and thus our start command is pretty verbose.Can I simply use the functionality provided in these examples:https://askubuntu.com/questions/277389/cron-job-to-restart-apachehttps://www.digitalocean.com/community/tutorials/how-to-use-a-simple-bash-script-to-restart-server-programsOr do I need a much more complicated process to make this happen?The command we use to initially start the server ispython manage.py runmodwsgi --host 0.0.0.0 --port 8001 --https-port 8000 --ssl-certificate (certificate Location) --server-name (Domain Name)I'm pretty new to Linux and using both Mod-wsgi as well as Apache so any help is greatly appreciated.
Using a Cron Job to check if my mod_wsgi / apache server is running and restart
You have to use "EndAt"and"RepeatForever" together:ITrigger trigger = TriggerBuilder.Create() .WithDescription("Minute") .WithSimpleSchedule(x => x .WithIntervalInMinutes(minutes) .RepeatForever()) .StartAt(DateBuilder.DateOf(StartHour, StartMinute, StartSeconds, StartDate, StartMonth, StartYear)) .EndAt(DateBuilder.DateOf(endMinnutes,endSeconds,endDate, endMonth, endYear)) .Build();The default behavior of scheduler is repeatedcount 0. when repeatedcount is 0, the method "FinalFireTimeUtc" returns the start date. you will stop raising events only when "FinalFireTimeUtc" returns null.To achieve the behavior you are looking for, you have to use "EndAt" and "RepeatForever" together
I have the below simple trigger which runs every 60 minutes. I want this to end on a given date. How can I achieve this?ITrigger trigger = TriggerBuilder.Create() .WithDescription("Minute") .WithSimpleSchedule(x => x .WithIntervalInMinutes(minutes)) .StartAt(DateBuilder.DateOf(StartHour, StartMinute, StartSeconds, StartDate, StartMonth, StartYear)) .Build();I tried the .EndAt after the .StartAt line. But it doesn't work. Please advice
How can I specify end time for a quartz.net simple trigger on minute recurrence?
If each one of these is a new line you could try:$s =~ s/remote_phonebook\.data\.1\.name =( Users|$)/remote_phonebook.data.1.name = Users/;If not, please let me know on the comments.
I have a perl script in a cron that runs every X minutes. It is suppose to find a string and replace it with a string with more data:s/remote_phonebook.data.1.name =/remote_phonebook.data.1.name = Users/;I would expect it to look like this:before:remote_phonebook.data.1.name =after:remote_phonebook.data.1.name = Usersthe first time it runs it works fine. However, each additional time it appends to the end of the line so 3 cron jobs later i see:remote_phonebook.data.1.name = Users Users UsersHow can make it so if "Users" doesn't exist, add it, if it exists, ignore?
perl search replace is appending not replacing
Your job will need to implement theStatefulJobinterface. It is a marker interface that tells Quartz that it should not trigger the job if it is still running. In other words it prevents concurrent executions of the job.
I am using Quartz scheduler to schedule the process of file download from SFTP. The job triggered after every 2 hrs. But sometimes due to huge file size, downloading takes more time and before it completes, the process is restarted. Is their any way we can hold the scheduler to trigger same job again till the previous process completes processing?I m using quartz 1.8.5. Below is code<flow name="quartzCronModel"> <quartz:inbound-endpoint connector-ref="Quartz" jobName="cron-job" cronExpression="${database_download_timer}" encoding="UTF-8"> <quartz:event-generator-job /> </quartz:inbound-endpoint> <component doc:name="Download Database" class="com.org.components.sftp.FileTransfer"> <method-entry-point-resolver acceptVoidMethods="true"> <include-entry-point method="execute" /> </method-entry-point-resolver> </component> </flow>I am reading cron expression from a properties file.
Holding Quartz scheduler to trigger job again till previous job finish processing
Such a picky syntax...8 10 * * 6 expr `date +\%W` \% 2 == 1 >/dev/null || /path/to/script/scriptToRun.shFirst, the cronjob:+---------------- minute (0 - 59) | +------------- hour (0 - 23) | | +---------- day of month (1 - 31) | | | +------- month (1 - 12) | | | | +---- day of week (0 - 6) (Sunday=0 or 7) | | | | | * * * * * command to be executed 8 10 * * 6So in this case it means that the cronjob gets executedevery Saturday at 10.08.Then,man datesays:%Wweek number of year, with Monday as first day of week (00..53)$(date +\%W) \% 2 == 1 >/dev/nullmeans: if the week number is not multiple of 2, then send the output to dev/null. Otherwise, proceed normally.So the script gets executedevery other Saturday at 10.08.
I see this cron setting in a crontab and I am curious as to when the script actually gets executed.8 10 * * 6 expr `date +\%W` \% 2 == 1 >/dev/null || /path/to/script/scriptToRun.sh
When does this cron job get executed?
Call a wrapper script every minute. This wrapper script looks at (minutes % 3) and calls the correct script using the remainder.Only one line in cron: nice.EDIT: New thoughts You can skip the wrapper by introducing an ugly crontab line.I would go for the wrapper (cleaner crontab, place to set and export variables, additional control statements), but I think you should know about the possibilities.Make the testfiles x0, x1 and x2 in /tmp, chmod +x them, with the contentecho $(date) $0 >> /tmp/x.outMake a crontab line* * * * * /tmp/x`echo "$(date '+\%M') \% 3" | bc`Wait 5 minutes (maybe get coffee black for me?) and look at /tmp/x.out.Remove the crontab entry and the new /tmp/x* files.
I have three scripts and want every one of them to run every 3 minutes, but in way that every minute a different script is running.for example00:00 script1 is executed 00:01 script2 is executed 00:02 script3 is executed 00:01 script1 is executedIs there a way to make this work via crontab in Debian?At the moment I have it like this:*/3 * * * * php /Scripts/script1.php &> /dev/null */3 * * * * php /Scripts/script2.php &> /dev/null */3 * * * * php /Scripts/script3.php &> /dev/nullbut this would run all the scripts all 3 minutes
special cronjob scheduling
You havespoolfile=$SCRIPTPATH/textfile1.txt spoolfile2=$SCRIPTPATH/textfile2.txtand then latervalue1=`/usr/bin/cat textfile1.txt` value2=`/usr/bin/cat textfile2.txt`looks like the textfiles are saved in one place and read from another.
I am new on writing Unix shell scripts. I have written a script which include Oracle Database sql codes. As you see below, it writes outout of sql codes on text files and i want to send these outputs by mail. It works very well when i run it manually. But when on crontab it does not do it as i want. Sql codes work very well, text files are updated, it sends mail but values are blank in mail. I read some other problems, i wrote all paths but i could not find the problem. I hope you can find the solution. Thank you, best regards#!/usr/bin/ksh ./home/partner/.profile NLS_LANG=AMERICAN_AMERICA.WE8ISO8859P9 ORACLE_BASE=/oracle ORACLE_SID=---------------- ORACLE_HOME=------------- USER=------------ PASSWD=-------------- SCRIPTPATH=/home/path-to/scripts/ spoolfile=$SCRIPTPATH/textfile1.txt spoolfile2=$SCRIPTPATH/textfile2.txt export NLS_LANG ORACLE_BASE ORACLE_SID ORACLE_HOME $ORACLE_HOME/bin/sqlplus $USER/$PASSWD<<EOF @$SCRIPTPATH/code1.sql $spoolfile exit; EOF $ORACLE_HOME/bin/sqlplus $USER/$PASSWD<<EOF @$SCRIPTPATH/code2.sql $spoolfile2 exit; EOF value1=`/usr/bin/cat textfile1.txt` value2=`/usr/bin/cat textfile2.txt` if [[ -s $spoolfile ]] ; then echo "mail1 "$value1 "text "$value2 | mailx -s "subject"[email protected]else echo "mail2" | mailx -s "subject"[email protected]fi
Scripts works perfect when i run it manually, but on crontab something is wrong
This happens due to misfire policy. Trigger missed its fire time, is considered misfired and then action is taken according to misfire policy.You can adjust triggers misfire policy when creating the trigger. Please see the tutorial for more information.http://www.quartz-scheduler.net/documentation/quartz-2.x/tutorial/more-about-triggers.htmlhttp://www.quartz-scheduler.net/documentation/quartz-2.x/tutorial/crontriggers.html
I am adding Triggers to myQuartz.NETscheduler using statements like this:ITrigger t = (ICronTrigger)TriggerBuilder.Create() .WithIdentity(triggerName, triggerGroup) .WithCronSchedule(cron) .Build();Say, the cron expression is one to fire every 3 minutes:0 0/3 * 1/1 * ? *In my program, the user canPauseandResumea job that has been scheduled with the above schedules.What I see is that every time I resume a pause job, the job is executed onceimmediatelyafter resume. This has started to worry me. Is this behavior normal or is there a way to avoid this?
Cron triggers fires immediately after resume
You dont want to run the CRON every minute instead create a specific job for your user and run it once. Something like this should work (untested - on mobile)$your_users_date; $cmd = "sudo crontab -l | { cat; echo ". date("i H d m",strtotime($your_users_date))." * php /path_to_your_script.php arg1 arg2; } | crontab -"; shell_exec($cmd);This will append a job to the crontab at the time your user has defined
I want to create a cron job which will run with the user define time in database. For eg.User can set start time and end time in the database .When the end time is reached I want cron to trigger one script to send mail.First of all Is it possible in cron or I have to go with some different approach ? and this all things will be done on AWS EBS. Below is what I tried on my local machine to just send a simple mail which is too basic*/1 * * * * /usr/bin/php -q/var/www/html/cronTry/cron.php
Create a cron job with user define dtime
There must be some error in your XML. Usually Quartz logs it when the Factory job of re-reading XML works. Quartz XML parser is very particular in what order you are mentioning the properties of a job, Like where should the misfire-instruction of a trigger is mentioned etc. Kindly look for errors, you will easily find the error.
I've got about 25 jobs defined in XML on a simple Java Web application I have running with Quartz Scheduler.I noticed a while back that some of my jobs were not running when they were meant to. The cron expressions are definitely correct, and the xml file is definitely correctly defined - the xml parsing plugin is quite picky and it doesn't mention any errors.I had all of these jobs categorised into seperate files. To try and isolate the issue, I decided to create one file to house all of the jobs. After doing this, it seems that the first 5 jobs in the file run.The 6th job won't run, but if I move it up one position in the file (to 5th position) - it runs correctly.Quartz.properties:org.quartz.scheduler.skipUpdateCheck: true # ----------------------------- XML Trigger Files ------------------# org.quartz.plugin.jobInitializer.fileNames = all_jobs.xml # ----------------------------- Threads --------------------------- # # How many jobs can run at the same time? org.quartz.threadPool.threadCount=500 # ----------------------------- Plugins --------------------------- # # Class to load the configuration data for each job and trigger. # In this example, the data is in an XML file. org.quartz.plugin.jobInitializer.class=org.quartz.plugins.xml.XMLSchedulingDataProcessorPluginIs there some sort of thread limit specifically for jobs defined in XML that I obviously don't know about?Any help would be greatly appreciated.Thanks!
Quartz Scheduler (Java) - limint on XML-defined jobs
You may still opt for using Quartz if:An event needs to be scheduled as part of the activity that happens within the java application itself. For example, user subscribes to a newsletter.You have a listener object that needs to be notified when the job completes.You are using JTA transactions in your scheduled jobYou want to keep the history of job executions or load job and trigger definitions from a file or a databaseYou are running on an application server and require load balancing and failoverYou are not running on an UNIX / Linux environment (i.e. you wanted platform independence)
In my project I required to write some background jobs for scheduled processing. I did it using quartz scheduler with spring, but quite often it required me to execute the tasks at random without schedule. So later I pulled out the tasks from the quartz and created web endpoints for them(exposed internally).To perform the regular scheduled based operation of tasks, I created unix cron jobs that hit the web endpoints using curl command.My question is, why could this approach not work always. Even in case you don't want to expose web endpoints, you can always execute standalone tasks using unix cron. Is there any particular advantage I gain by using quartz scheduler over unix cron jobs?
Unix Cron Job vs Quartz scheduler
Sounds like you have two different versions of Octave installed. One in/usr/bin/octave(an older version without the--force-guioption), and a new version that is in your path but not on the path when cron runs.Typewhich octaveto see where is the octave version you want to run and fix your paths. You may want to uninstall the old version of Octave too.
I would like to use a cronjob to open octave with the force-gui option.Writing00 22 * * * octave --force-gui > ~/log 2>&1doesn't start octave but gives the log messageoctave: unrecognized option '--force-gui' usage: octave [-HVdfhiqvx] [--debug] [--echo-commands] [--eval CODE] [--exec-path path] [--help] [--image-path path] [--info-file file] [--info-program prog] [--interactive] [--line-editing] [--no-history] [--no-init-file] [--no-init-path] [--no-line-editing] [--no-site-file] [--no-window-system] [-p path] [--path path] [--silent] [--traditional] [--verbose] [--version] [file]When I enteroctave --force-guidirectly in the terminal, octave opens just fine.I noticed that the same error as in the log file is produced when I enter/usr/bin/octave --force-guiinto a terminal.Question:How can I start the octave GUI via Cron?I am using Octave version 3.8.1 on Linux Mint 16.
Start octave with GUI from cron
That's why we haveenv, which is guaranteed to be in/usr/bin, so all you have to do is:/usr/bin/env wget [options] [url]And you're good to go, provided the user running the PHP script has the correct permissions to executewget, write the downloaded files to the specified path etc... but that's a different matterOn the other hand, because you've tagged this question with thecrontabtag, make sure the hashbang at the top of your script usesenv, too:#!/usr/bin/env php <?php //your script hereThen,wgetwill be callable (again: if the environment variables, and permissions check out) plain and simple:#!/usr/bin/env php <?php exec('wget --help', $output); var_dump($output);Should yield zomething like:array(172) { [0]=> string(51) "GNU Wget 1.15, a non-interactive network retriever." [1]=> string(32) "Usage: wget [OPTION]... [URL]..." [2]=> string(0) "" [3]=> string(72) "Mandatory arguments to long options are mandatory for short options too." ...Tried it on my machine, no problems whatsoever
Is it possible to determine where thewgetbinary is located using PHP? I'm trying to create a softcodedwgetcron command for my users. I know that in most environments, thewgetlocation will already be included in thePATHbut cron doesn't always share the same environment. To play it safe, I want to use an absolute path like/usr/bin/wget.Is there a constant similar toPHP_BINDIR? I cannot assumewgetwill be in the same location as PHP, right? Any other ideas?Thanks for any help!
Find wget Location Programmatically using PHP?
Enable user to run cron jobsIf the/etc/cron.allowfile exists, then users must be listed in it in order to be allowed to run the crontab command. If the/etc/cron.allowfile does not exist but the/etc/cron.denyfile does, then users must not be listed in the/etc/cron.denyfile in order to run crontab.In the case where neither file exists, the default on current Ubuntu (and Debian, but not some other Linux and UNIX systems) is to allow all users to run jobs with crontab.Add cron jobsUse this command to add a cron job for the current user:crontab -eUse this command to add a cron job for a specified user (permissions are required):crontab -u <user> -eAdditional readingman 5 crontabCrontab in Ubuntu:https://help.ubuntu.com/community/CronHowto
I am trying to backup postgres databases. I am running a cron job to do so. Issue is that postgres runs under user postgres and I dont think I can run a cron job under ubuntu user. I tried to create a cron job under postgres user and that also did not work. My script, if login as postgres user works just fine. Here is my script#!/bin/bash # Location to place backups. backup_dir="/home/postgres-backup/" #String to append to the name of the backup files backup_date=`date +%d-%m-%Y` #Numbers of days you want to keep copie of your databases number_of_days=30 databases=`psql -l -t | cut -d'|' -f1 | sed -e 's/ //g' -e '/^$/d'` for i in $databases; do if [ "$i" != "template0" ] && [ "$i" != "template1" ]; then echo Dumping $i to $backup_dir$i\_$backup_date pg_dump -Fc $i > $backup_dir$i\_$backup_date fi done find $backup_dir -type f -prune -mtime +$number_of_days -exec rm -f {} \;if I dosudo su - postgresI see-rwx--x--x 1 postgres postgres 570 Jan 12 20:48 backup_all_db.shand when I do./backup_all_db.shit gets backed up in/home/postgres-backup/however with cronjob its not working, regardless if I add the cron job under postgres or under ubuntu.here is my cronjob0,30 * * * * /var/lib/pgsql/backup_all_db.sh 1> /dev/null 2> /home/cron.errWill appreciate any help
issues backing up postgres databases in cron
You can schedule a cron job to run every hour, because every hour there is 9 am somewhere.
I want to schedule a task for 9:00 AM in every country. (basically 9:00 AM in every time zone). How can I schedule that in google appengine?Will it take multiple timezones for time zone parameter?Thanks in advance
Multiple Time Zones in Google Appengine Cron Job
Ditch thesleep, and use the cron.In your console typecrontab -eSet up the following;*/20 * * * * php -f path/to/script.phpInstall crontab on CentOSWindows scheduled taskAdd Jobs To cron Under Linux or UNIX
So i have written a program to call API from a website each 20 minutes. i"ve done this by giving the sleep() function in php. i have given this delay inside a while loop. how can i execute the same function using cron? this is the while loop..<?php @ini_set("output_buffering", "Off"); @ini_set('implicit_flush', 1200); @ini_set('zlib.output_compression', 0); @ini_set('max_execution_time',0); //code; while($r=mysql_fetch_array($res)) { //code; if(sleep(1200)!=0) { echo "sleep failed script terminating"; break; } flush(); ob_flush(); } ?>
should we use cron if we are using delay in our program...?
This is likely an issue of the cron environment not having the environment variables set up by your ssh agent. Therefore when git makes an ssh connection, it can't authenticate, because it can't contact your ssh agent and get keys.This answer probably has what you're looking for:ssh-agent and crontab -- is there a good way to get these to meet?If for some reason it's not ssh-agent related, tryprint os.environat the top of your script to dump the value of all environment variables.Compare the output from cron and runningenvin your bash shell. There are likely some differences, and one of them is the source of your error.If you set up the same environment variables in your shell as you have in cron, the behavior should reproduce.
The entire script runs fine. I will also note that if I copy and paste the cron job into the shell and run it manually it works with no issues.Base = '/home/user/git/' GIT_out = Base + ("git_file.txt") FILE_NAME = Base + 'rules/file.xml' CD_file = open(Base + "rules/reports/CD.txt", 'r') os.chdir(Base + 'rules') gitFetchPull = "git fetch --all ;sleep 3 ; git pull --all" git1 = subprocess.Popen(gitFetchPull, shell=True, stdout=subprocess.PIPE) gitOut = git1.stdout.read() print(gitOut)When I read the output from cron it appears to not be able to authenticateReceived disconnect from 172.17.3.18: 2: Too many authentication failures for tyoffe4 fatal: The remote end hung up unexpectedly error: Could not fetch origincron job* * * /usr/bin/python /home/tyoffe4/git/rules/reports/cd_release.py >/home/tyoffe4/git/rules/reports/cd_release.out 2>&1
Git fetch failing in cron. Runs fine manually
The cron will boot up a new PHP process every minute, and they will all operate simultaneously with various terrible results (unless your script is properly guarded against such things, anyway)After a while, either you'll constantly have a number of simultaneous requests running OR your server will crash after running out of resources, depending on whether or not the scripts start blocking each other due to trying to access restricted resources.Either way, it probably won't be pretty and it probably won't be what you want.
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.Closed9 years ago.Improve this questionim wondering what would happen if a cron job is set to run every minute but the script it runs takes 2 minutes to run? Would it queue itself, ignore runs if previous cron is still running or run the same file simultaniously? Thanks!
Cron faster than script [closed]
crontabdoes not accept a shebang (and the shebang is wrong anywaythat's obviously just a Markdown problem which has been fixed). Try, for instance,SHELL=/bin/bash * * * * * find /tmp/sess_* -mtime +2 -exec rm {} \;if you want to run the job every minute. Seeman 5 crontabfor details.Update:Q:What does the* * * * *in the minimal crontab above mean?A:Those five fields are date and time fields controlling when the job is executed.According toman 5 crontab,The time and date fields are:field allowed values ----- -------------- minute 0-59 hour 0-23 day of month 1-31 month 1-12 (or names, see below) day of week 0-7 (0 or 7 is Sun, or use names)So, here are some examples:* * * * *: every minute;00 * * * *: the beginning of every hour;00 03 * * *: 3 a.m. every day;00 03 01 * *: 3 a.m. on the first day of every month;00 23 * * 0: 11 p.m. every Sunday;00 23 * * Sun: same as above;*/15 * * * *: every fifteen minutes.You can get more examples and explanations by Googling things like "vixie cron tutorial".
My issue.I need to remove session files that are stored on the server in the /tmp folder older than 2 days.I've added this in crontab in terminal.#!/bin/bash find /tmp/sess_* -mtime +2 -exec rm {} \;I save it out but keep getting bad minute error, can anyone help and let me know where I am going wrong.Thanks.
Ubuntu Crontab Edit
You can set vi as your default crontab editor using the command. export EDITOR=viThen you can save and exit crontab using :wq.
I am new to linux centos ,i am trying to save and exit crontab in centos.I have used CLI.crontab -ewhen i press esc key from my keyboard it says ":quit to exit: and i press ":quit" and press enter key from keyboard crontab exit without saving.
unable to save crontab file using CLI
We can set cron on our localhost through following steps:Open crontab in your terminal:EDITOR=gedit crontab -eAdd your cron settings at the end of your file (we are setting cron to be execute in every 2 minute in our example):*/2 * * * * /usr/bin/php -q /path/to/phpfile.php > /dev/nullSave your cron file and run:sudo service cron restart
I want to execute a PHP script on my localhost in Ubuntu. I have tried a lots of methods to apply cron but no luck!
How to set cron in to run PHP file on localhost in Ubuntu?
If you want what @Duncan said (a cron expression that finds the first working day in September), then this should do:0 0 0 1W 9 ? *Results:Tuesday, September 1, 2015Thursday, September 1, 2016Friday, September 1, 2017Monday, September 3, 2018Monday, September 2, 2019
How to create a cronexprrssion for ever 1st September working day. It means omit Sunday
Cron expression for every sept working day
As commented above, there are many things that are likely to cause the problem. Probably, the need to set the full path in the commands you use.Fromhttps://stackoverflow.com/tags/crontab/infoCommon problems uncovered this way:foo: Command not found or just foo: not found.Most likely $PATH is set in your .bashrc or similar interactive init file. Try specifying all commands by full path (or put source ~/.bashrc at the start of the script you're trying to run).Also, I want to indicate another way to do this block of code:TOTAL=$(df / -h | grep / | awk '{ print $2}' ) USED=$(df / -h | grep / | awk '{ print $3}' ) AVAILABLE=$(df / -h | grep / | awk '{ print $4}' ) PERCENTAGE=$(df / -h | grep / | awk '{ print $5}' )Note that you are callingdf -h /four times, while one suffices:read _ TOTAL USED AVAILABLE PERCENTAGE _ < <(df -hP / | tail -1)Wheretail -1is used to remove the header.sed '/Filesystem/d'could also be used.Or if you want to use a line for each one of them, do:TOTAL=$(df / -hP | awk '/\// { print $2}' ) ^^^^ filter lines containing /Note the usage of-Pindf, that stands forPortability (or--portability, "use the POSIX output format"), used to prevent lines being split if they are too long.Thanks to Etan Reisnerfor this.
I am trying to create a cron that every 2 days send the current space usage in an email to myself.I can run the script perfectly and the email is sent but when I put it in the cronlist doesn't send the email.The cron is active because I created a file that outputs the current date to a file and put it in the cronlist and it has been working.This is my email script#!/bin/bash TOTAL=$(df / -h | grep / | awk '{ print $2}' ) USED=$(df / -h | grep / | awk '{ print $3}' ) AVAILABLE=$(df / -h | grep / | awk '{ print $4}' ) PERCENTAGE=$(df / -h | grep / | awk '{ print $5}' ) EMAILSUBJECT="Server 79.XXX.XXX.XXX" sendmail "[email protected]" <<END Subject: $EMAILSUBJECT Disk usage on Server 79.XXX.XXX.XXX Total space: $TOTAL Used space: $USED Available space: $AVAILABLE Percentage: $PERCENTAGE ENDThis is the test output for the crontab -l[root@server ~]# crontab -l 0 * * * * /usr/sbin/ntpdate ntp.blacknight.ie 0 21 * * * /bin/nice -n 10 /usr/local/directadmin/plugins/awstats/hooks/cgi-bin/updateall.sh * * * * * bash /root/checkspace.sh * * * * * bash /root/test.shThe test.sh is the one that outputs the date, and the file is being filled.Thecheckspace.shsends the mail, and if I typebash /root/checkspace.shin the command line the email is sent, but the cron doesn't work.Is there any kind of incompatibility between the cron and the mail??
Cron with sendmail incompatibility
java7 WatchService meet your requirements, code as followWatchService watchService=FileSystems.getDefault().newWatchService(); Paths.get("/opt").register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY); while(true) { WatchKey key=watchService.take(); for(WatchEvent<?> event:key.pollEvents()) { System.out.println(event.context()+" happen "+event.kind()); } if(!key.reset()) { break; } }
I need to trigger a process in remote node when a file changes in different remote node. Scenario is like this. There is a cron running at an unknown time in a remote node. Cron triggers some process which will change some files in the same node. What I need to do is that, when those files change I need to perform parsing of those files and populate it in database in someother remote node.How can I make this happen. How to get to know when the file changes in a node and trigger a .sh file when any change is found in a different node.
Trigger a process on change of a file in unix
In your case30 05 05 03 * command to be executed - - - - - | | | | | | | | | +----- day of week (0 - 6) (Sunday=0) | | | +------- month (1 - 12) | | +--------- day of month (1 - 31) | +----------- hour (0 - 23) +------------- min (0 - 59)??says that you don't mind the day of the week because you are already stating the exact date. If you place the01it would still run but its redundant.
I am new to LINUX. I have a clear idea on how cron works, but suddenly a small doubt struck at my mind. Suppose if I want to executelscommand on 5th march 5.30AM, then mycroncommand will be30 05 05 03 ??ls.My simple question is that what entry will come on??place. And suppose if I enter01in that position instead of??, what will happen. Please excuse me if this is a simple question and please help me solve the same.
Fifth field of crontab
Scheduling a Java EE 7 Batch job can be done in couple of ways:Using @Schedule annotation which supports cron-like syntaxUsing ManagedScheduledExecutorServiceMore details at:http://blog.arungupta.me/2014/07/schedule-javaee7-batch-jobs-techtip36/If you want to invoke using curl, then you can put the code in a REST endpoint using @GET annotation. Add a command to invoke this endpoint in crontab.
JavaEE 7 appservers support batch operations implementing JSR 352 (Glassfish and Wildfly do).What is a good way to start batch operations from Unix cron?exec wget/curl a rest servlet that starts the batchexec java that calls via JMX the appserver (slow java start, is there a JMX for C?)??
trigger Java EE batch from cron
<?php add_filter( 'cron_schedules', 'cron_add_day' ); function cron_add_day( $schedules ) { $schedules = array( 'day' => array( 'interval' => 86400*1, 'display' => __( 'Every Day' ) ), ); return $schedules; } ?>
I want to run a cron job in wordpress using the default function. I want set the time to run every 15 days. How can I set the the for this?function prefix_deactivation() { wp_clear_scheduled_hook('prefix_hourly_event_hook'); } register_deactivation_hook(__FILE__, 'prefix_deactivation'); function prefix_activation() { wp_schedule_event(time(), 'everyminute', 'prefix_hourly_event_hook'); } register_activation_hook(__FILE__, 'prefix_activation'); /* On activation, set a time, frequency and name of an action hook to be scheduled. */ function prefix_do_this_hourly() { // do something every hour cronjob_options(); } function cronjob_options() { /* your job */ } add_action('prefix_hourly_event_hook', 'prefix_do_this_hourly');
cron job in wordpress
Unless you're runningBSD ps, you should be able to use a-Cflag orpgrep-C cmdlist Select by command name. This selects the processes whose executable name is given in cmdlist.For example,if ps -C node > /dev/null then date > /etc/nodeCheck.log else date > /dev/null fiorif pgrep node > /dev/null then date > /etc/nodeCheck.log else date > /dev/null fi
There is some weird behavior going on that leads me to think there may be something going on...So I have a shell script executed by cron. Basically it is meant to check if Node.js is running. If so, log the date... if not then log nothing! At the time I built it I tested it and saw it logged when a node script was running and did not log when it stopped running...Recently I knew Node went down and thought it was the perfect opportunity to check if the script did what its supposed to do. Itdidnt! And itdoes not... :(Here is the script:#!/bin/bash if ps -Al | grep -v grep | grep -q node then date > /etc/nodeCheck.log else date > /dev/null fiPermissions on this .sh are correct, paths used exist, running$ps -A | grep -v grep | grep -q nodereturns nothing and$echo $? 1So shouldn't it be going to the else block? node is a process started after bootup. The shell script does not work correctly both when run by cron or by me when I am SSH'd in.Am I missing something fundamental here?TIANiko
Shell script to check if process is running
You need to save the cronjob, that's all that's missing:#!/bin/python from crontab import CronTab cron = CronTab(user=True) job = cron.new(command='python3 /opt/my_script.py') job.minute.on(2) job.hour.on(12) cron.write()
I am trying to add a line to my system user's crontab, from a Python script which uses the package python-crontab. My crontab file does not exist yet, and when I run this code, nothing happens (no errors, no results, no creation of crontab file):from crontab import CronTab cron = CronTab(user=True) # cron = CronTab(user='my_user') I tried this line too without any results job = cron.new(command='python3 /opt/my_script.py') job.minute.on(2) job.hour.on(12) True == job.is_valid()Am I missing anything?
Create crontab with python-crontab in Python?
Easy enough to test.for a in {1..3}; do mkdir -p /tmp/backup/${a}; done find /tmp/backup/ -maxdepth 1 -type d -mmin +1This returned/tmp/backup /tmp/backup/2 /tmp/backup/1 /tmp/backup/3Butfind /tmp/backup/* -maxdepth 1 -type d -mmin +1returned/tmp/backup/2 /tmp/backup/1 /tmp/backup/3Add a asterix
I have a cron job that creates folders within the "backup" directory \tmp\backup.I am looking to have a second job to delete folders within "backup" which are older than 1 minute using the job below55 19 * * * find /tmp/backup/ -maxdepth 1 -type d -mmin +1 -execdir rm -rf {} \;But this job deletes the parent directory "backup" too, I am confused on where I am going wrong. Any help is appreciated !
Cron to delete folders older than required time deletes parent folder
From your current crontab file, you're basically runningroot /home/grantmcgovern/Developer/Projects/StudyBug/Main.pyevery time.If you want to run it as root, usesudo crontab -eand put43 14 * * * /usr/bin/python /home/grantmcgovern/Developer/Projects/StudyBug/Main.pyinstead.
I have a python script I want to fire off every night at midnight. I'm using cron scheduler right now to do so, however, I can't figure out why it's not working. For now, I've been using close times (within the next minute or so) to test the cronjob, but I will ultimately want it to work for midnight.Here is what I put in my crontab file (to run for 2:43pm), hosted on my ubuntu machine:43 14 * * * root /home/grantmcgovern/Developer/Projects/StudyBug/Main.pyI even put the:#!user/bin/pythonon top of all the .py files.I also did:chmod +x "scriptname".pyFor each of the .py files and still no luck. Am I missing something blatantly obvious? I should note, this is my first time playing with cron tasks.
Cron task python script not working
The problem is thatAppShelldoesn't support view functional by default. So like insimilar question, you have to add following:App::uses('View', 'Core'); $view = new View(); $view->set(compact('data', 'cmsoptions')); $view->layout = 'pdf'; $pdfContent = $view->render();And then you can use$pdfContentas content of PDF file with help offile_put_contents('/var/www/new_invoice.pdf', $pdfContent);or similar.
I'm using CakePHP 2.4 in and TCPDF to generate invoices.A cronjob checks every day if new invoices shoot be generated.When I access the function via a browser, everything works perfect.When i access the function via the shell, I get an error:CronjobShell.php:$cmsoptions = $this->Cmsoption->find('first'); $this->set(compact('data', 'cmsoptions')); $this->layout = 'pdf'; $this->render();"Call to undefined method CronjobShell::set()"I understand that the Set option is ginving the problem. But how can I generate the PDF with a Cronjob?
CakePHP Shell Cronjob TCPDF
Pass the URL to the cron script, for example as environment variable or CLI argument:*/1 * * * * SITE_URL=example.com /usr/bin/php /pathto/send.php # or */1 * * * * /usr/bin/php /pathto/send.php example.comIn the script:$siteURL = getenv('SITE_URL'); // or $siteURL = $argv[1];That's a better alternative to a) exposing your cron script publicly through the web server and b) going the long way round through an HTTP request for something that doesn't need it.
Suppose I have asend.phpfile, which include a function to get the site's URL (for example, unsubscribe an email), but the emails are auto-send by a cron command, it seems in this case the siteurl will not work properly, since local script has no URL at all?Of course I can set the right URL exactly in thesend.php, but if I don't want to do this, is there any solution?EDIT//siteurl in send.php function siteURL(){ $protocol = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://"; $domainName = $_SERVER['HTTP_HOST']; return $protocol.$domainName; }cron#cron to excude send.php */1 * * * * /usr/bin/php /pathto/send.php
How to cron a php with siteurl?
You could try to edit the default crontab directly:Edit/etc/config/crontabvia WinSCP or open it withcrontab -eAdd your entry* * * * * /path/to/script/cron/dashboard.phpExecute the commandcrontab /etc/config/crontabAnd finally restart the cron-service with/etc/init.d/crond.sh restartAfter those steps, the cron-service should execute the cron-jobs.
Im trying to run a Script with Cron:The Cron I used:ssh: crontab /test.txttest.txt:* * * * * /path/to/script/cron/dashboard.php(I set the Interval to every minute to check if it works)dashboard.php:<?php $con=mysqli_connect("localhost","myuser","mypw","mydb"); $randomnumber = rand(1000,3000); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } mysqli_query($con,"INSERT INTO dashboard (count, date) VALUES ('$randomnumber', NOW())"); mysqli_close($con); ?>I inserted the crontab viacrontab /test.txt(located in root).Then executed this line (I followed this tutorial:Qnap Turorial for Crontabs):/etc/init.d/crond.sh restartAnd I tried to open the Script in a Browser and it worked (I had a new row in my table with a random number and the current date. But If I check my Database every minute nothing new is added through the cron tab..I run the System through my QNAP NAS...
Execute PHP Script through Crontab Qnap NAS
You have to not useTimer(or anything else that uses threads via the normal Java API). AppEngine doesn't allow creation of additional threads as part of a request except viaits own special interface(and they're not allowed to outlive the request).The point of crons is that they're already called once for each time they're supposed to happen. You don't need to do any further "scheduling" in the servlet - just do what you want to happen when the cron fires.
What else do I have to do, other than making acron.xmlfile for scheduling ? I am getting the same exception:java.security.AccessControlException: access denied ("java.lang.RuntimePermission" "modifyThreadGroup")as I was getting before.This is mycron.xml:<?xml version="1.0" encoding="UTF-8"?> <cronentries> <cron> <url>/tw</url> <description>Tweet every half an hour</description> <schedule>every 30 minutes from 8:00 to 17:00</schedule> </cron> </cronentries>/twis the servlet that has adoGetmethod which usesjava.util.Timerto schedule the task.
What else do I have to do other than making cron.xml?
Not sure what detailed information or references there could be for a situation like this. It's not like someone commissions a study to look at this.Assuming your command is intelligent enough to only allow one execution at a time (which appears to be the case judging by the error message you posted) then the only ill effect is a few CPU clock cycles (I think).
I have a Cron Job scheduled to execute a command a few times a day. There are cases where the cron job isn't needed but will automatically run. If that happens the following error message shows:PM2 [ERROR] Script already launched, add -f option to force re executionNote: The Cron Job runs PM2 in reference to a script.Is there any negative effect to having the cron job run even if the script is already running?Please provided detailed information or references. Not just your opinion please.
Running Cron Job Even When Not Required
AQL is probably not in the PATH for the environment the script executes in. Try using the fully qualified path to AQL (e.g./full/path/to/AQL). In general, for this reason as well as for security, it's a good practice to specify fully qualified paths in scripts.
I have KSH script.If I run it manually using./scriptname.kshthen it would work fine.but if I set up a crontab job, I get error that AQL not found. (AQL is like SQL but not different).Here is my script code.#!/usr/bin/ksh AQL << EOF select count(*) from <tableT>; exitHere is crontab -e12 13 * * * /usr/users/somedir/dir3/dir4/scriptname.ksh > /usr/users/somedir/dir3/dir4/testz.txt 2>&1Here is what crontab runs and outputs to testz.txt/usr/users/somedir/dir3/dir4/scriptname.ksh: line 9: AQL: not found
KSH Script won't correctly when ran via Crontab job
Well, the command that works for you issudo tar -cvpzf backupfolder/localhost.tar.gz /var/wwwWhich means, you have to run the command with sudo access, and it will not work from within your crontab.I would suggest adding the cron job to the root user's crontab.Basically, dosudo crontab -eAnd add an entry there0 17 * * * cd /home/user/backupfolder && tar -cpzf localhost.tar.gz /var/wwwIf that doesn't work, add the full path of tar (like/bin/tar).Also, while debugging, set the cronjob to run every minute (* * * * *)
I am trying to archive my localhost's root folder with tar and want to automate it's execution on a daily basis with crontab. For this purpose, I created a 'backupfolder' in my personal folder. I am running on Ubuntu 12.04.The execution of tar in the command line works fine without problems:sudo tar -cvpzf backupfolder/localhost.tar.gz /var/wwwHowever, when I schedule the command for a daily backup (let's say at 17.00) insudo crontab -e, it is not executing, i.e. the backup does not update using the following command:0 17 * * * sudo tar -cpzf backupfolder/localhost.tar.gz /var/wwwI already tried the full pathhome/user/backupfolder/localhost.tar.gzwithout success.var/log/sysloggives me the following output for the scheduled execution:Feb 2 17:00:01 DESKTOP-PC CRON[12052]: (root) CMD (sudo tar -cpzfbackupfolder/localhost.tar.gz /var/www) Feb 2 17:00:01 DESKTOP-PC CRON[12051]: (CRON) info (No MTA installed, discarding output)/etc/crontabspecifies the following path:SHELL=/bin/sh PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/binI assume that crontab is not executing as this is a sudo command.Is there a way how I can get this running? What is the recommended, safe way if I don't want to hardcode my root password?
tar archiving via cron does not work
Well, php might be a little overkill. You can just usewget http://somesite.com/file.jpgto grab a file and download it.If, for some reason, you need to use PHP, you might want to try$file = file_get_contents('http://somesite.com/file.jpg');
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed10 years ago.Improve this questionAnybody know any php script witch is can download a file from the internet? I will wanna use with cron...
Download a file from the internet with php script? [closed]
Run Job is 3pm everyday. You use expression: 0 0 15 * * ?
I tried below two:CronSchedule("0 15 * * *") CronSchedule("0 0 15 ? * MON-SUN")Both triggers the process again after sometime.
How to run quartz scheduler everyday once at 3 PM
You may want to specify the full path to everything. Crons have a hard time finding things if they are not defined explicitly. Also if you have paths in test.sh you may want to specify them as well.Additionally, if you are having trouble but aren't sure why it's not working if you put MAILTO = 'your email address' at the top and get rid of the output piped to >/dev/null it may help you find out what the error is.
I have a script5 05 * * * /bin/bash -l -c 'nohup sh test.sh &'>/dev/null 2>&1It runs prefect in bash but when I put it in crontab it does not work. As it is running on remote server I thought maybe the time zone is the problem. I randateon the server and the output isFri Jan 10 05:10:02 UTC 2014. Why it does not work?
crontab job does not work
you're running php cron.php under yourself, but cron works under different user and even if you're trying to run it under www-data it is still different user from yourselfsimple solution: check what right has folder where php tries to write, set them to 0777 to test, check if cron script is successfulthen you can have different options, like - set folder's owner to cron and set 0755 or move cron user to the same group as you're
I'll start by saying I am very new to linux in general. What I have is a php script I wrote that fetches images from posts on reddit.com hides the post and adds the link to an array, then saves all the images in the array. when I type something like: "php cron.php" as root it runs fine, but whenever crontab runs it the script only hides all the posts but never saves the images. To me it sounds like a problem with permissions by the cron user. Ive been messing with it for hours and recently changed it the www-data user's crontab with: "su -l www-data -c 'crontab -e'" but still no cigar, since its a cron job I suppose its running silently and not giving me any errors. If anyone could show me how to display these messages it would surely help debugging. Thanks.
php script works when manually run but only partially works as cron job (will not write files to directory)
Create acustom commandand create a cron job to run it, also you can check somedjango appsfor manage cron jobs/repetitive tasks. I know you can use it on linux (in windows should be alternatives, I my head sounds now schedule task, but must there be other)
I have a django project and i need the ability for executing a function at a specified time on django server. for example you can consider that in my django project if a client request for friendship to another person if after (say) 7 days that person doesn't answer that request the request will be automatically removed. so i want the ability of calling a function on django server at a specified time that is stored in mysql table.
Run a script at a special time on django server
The answer is yes there is a way but how all depends on the slideshow you are using. If you didn't build it i would hunt for a function that's probably running at the end of the slideshow to trigger it to loop to the beginning. When you find that function you can alter it to run the script that connects to the API to get new images.You might have to delay the loop in the slideshow long enough for the new images to load.
I am new to php and database stuff, but have looked around and cannot find a solution.What I'm trying to accomplish:I have a slideshow of images. The images come from Flickr's API, stored in a database table, then the database data is generated into a JSON link.My question is, is there a way to execute the php script that calls the flickr API everytime the slideshow circle through all the images in the JSON link? I could specify every 1 minutes, but that may be too long if there are only a few images in the slideshow.If you can't do that,is there a way to execute the script every 1 minute on only fridays from 9pm EST to 3am EST?
Cron Job - How to execute a script between two times on specific days?
Use PHP - curl make a standard code and with the single you can upload data to server..http://coderscult.com/php-curl-tutorial-and-example/
I have a Cronjob which is done every ten minutes on my site, for example on the pagehttp://www.example.com/example.phpSometimes, in the administration panel of my website, when the admin have made some modification, i want to automatically launch the script on example.php.So my question is : Is there a way to visit an url, without showing it ? My goal is that the server read the page, not the admin, because the example files can be very heavy.I have read this thread, but it's not clear to me :How can I simulate a visit to a url?Thanks you for your advice !
Visit an url without showing
The most sure way is specify path to your interpreter. You should also change 5 to */5 (which mean run every five minutes nor than run at 5 minutes past each hour), try:*/5 * * * /usr/bin/php /path/to/your/script.php
I am using Ubuntu. Earlier I used to run cron jobs from GUI. I have created a php script and saved it on my server. i tried to execute cron from putty,5 * * * * path/folder/sample.php // script runs for every 5 minsBut it doesn't work.Am I in the right direction?Actually, where should be the command get executed dynamically?
cron command to execute a php script periodically
While there are other ways to do this, the cron will look like:* * * * * /usr/bin/curl "https://xxxxxxxxx.com/scheduled_messages".One of those other ways could berufus-scheduler.
I need a cron job to write into my crontab that every after one minute calls a URL of rails application that triggers a method and runs a scheduled job.I did not use whenever gem because it reboots the environment and i think it will strain my application. So i preferred to run a full system cron job independent of the rails app.The URL to be called ishttps://xxxxxxxxx.com/scheduled_messagespreferably being called usingcurl.The controller being called is ;class SchedulesController < ActionController::Base def scheduled_messages Schedule.scheduled_jobs render nothing: true end endand the methodSchedule.scheduled_jobsis here;def self.scheduled_jobs jobs = Schedule.where('execution_time <= ?', Time.now) if !jobs.empty? jobs.each do |job| task = Schedule.find(job) MessageWorker.perform_async(task.message_id, task.lists, task.user_id) task.destroy end end end
Cron job that calls a url for a rails app every 1 minute
According to my knowledge Scheduler is the best option. It is good and reliable go for it.
I know about Heroku Scheduler addon but is it very flexible like I want to be able run a task on the 1st and 15th of every month as well as at daily intervals.What else can I use or is Scheduler the best option for Heroku?
How do I implement something like cron job on Heroku?
Use a full path from the root of the filesystem, then both should be fine.
I wrote a php script to get my latest Twitter tweet and save it to a file. Here is the part doing so :// No errors exist. Write tweets to json/txt file. $file = $twitteruser."-tweets.txt"; $fh = fopen($file, 'w') or die("can't open file"); fwrite($fh, json_encode($tweets)); fclose($fh);This works fine when I run my php script directly in the browser, however, when I run the file from a cron job it creates the file in my user root directory (obviously not the correct place).If I change the above line to :$file = "public_html/get-tweets/".$twitteruser."-tweets.txt";the cronjob now works and saves to the correct location, but then manually running the file in my browser gives an fopen error that the file does not exist.What the heck is the problem? I need this to work both from cronjob and manually.
fwrite, fopen, and cronjob - not saving to proper location
I found a way to fire cronjobs without Unix installed on a machine.http://www.easycron.com/provides cron services:EasyCron is a task scheduler which provides services of calling URLs at specified time or by time interval. Once register with us, you get abilities to:Some of the features:Get Email notice about cron jobs' execution. (Applied to premium users)Random cron jobs.Cron job with cookies supported. (Applied to premium users)Cron job executed using POST method. (Applied to premium usersView execution logs of each cron job. (Applied to premium users)Cron job run time predictions. (Applied to premium users)Manage online cron jobs at your own user panel.Set cron job according to the date and time in your own account timezone.I am not conntected to this service in any way, but it provided the solution I was looking for.
Is it possible to create recurrent actions with PHP?I want to execute some statements every day at 10 o'clock. I know this could be done with cronjobs, but I only have a regular webhoster that doesnotprovide Unix access.
Does PHP provide a cronjob like function?
the files should be outside the web root, there's no need for them to be inside if they are only being called by cron. hope you are calling the file path and not the url?
How should I secure my cronjobs from being visited by search engines/visitors that write the correct URL in the headline?I have a cronjob, that is running every night, which transfers information to MailChimp, but if a user enters the URL correctly, he can make the cronjob run at anytime. How can I avoid this? :)Hope you have some ideas.Thanks in advance.
How to securely use cronjobs
the cron-job will simply execute a program on the (local) machine.a URL isNOTa program.it's a link to a ressource.whether this ressource triggers a PHP-script execution is not of cron's business.in any case, you could run a cron-job that will periodicallyvisita given URL. e.g. using thewgetcommand (a "non-interactive web-page downloader")*/2 * * * * wget --quiet -O /dev/null http://mydomain.com/_adder.php
I have a simply php script on my server and want it to be run every 2 minutes using a cron job.*/2 * * * * http://mydomain.com/_adder.phpI suspect the command syntax is wrong.Do I need to add a command before the script url? Another way to run the script?Any help is very much appreciated.
How to write a Cron Job to execute simple php script?
This should do itdrush vset cron_safe_threshold 0
Is there any easy way to turn off Drupal cron like setting 'Never' in admin/config/system/cron? Need to use such command in Jenkins bash script for automatic Drupal instance spin-up
Drush or bash command to turn off default Drupal cron
Make the cron script retrieve:http://yourdomain.com/path/to/script.php?token=743cc5a35d28aa7d22d4e93and then in the script:if( ! ( isset($_GET['token']) && $_GET['token'] === '743cc5a35d28aa7d22d4e93' ) ) { exit; }It doesn't guarantee that the request is genuine, but it will prevent accidental invocation of your script.
I am using Zend framework. I want to create an easy script for sending me an email with statistics every day. That is the easy part.The cron script execution with my provider can be only set up by an URL link.How can I make sure this URL can be only accessed by the machine, and not by any user or robot that tries the URL by accident or something.I want to avoid executing the cron script by anyone else than the machine that is supposed to access it.
accessing cron script in Zend
The issue is the%character in the crontab entry. In order to use%, you'll have to escape it. The following entry worked for me# ~/test.sh 1 $(date --date="next day" +"%Y-%m-%d") 40 12 * * * ~/test.sh 1 $(date --date="next day" +"\%Y-\%m-\%d")
Suppose I have the following shell script named test.sh.#!/bin/bash echo $1 $2I have the following command on my crontab.date=`date --date="next day" +"%Y-%m-%d"` 40 12 * * * ~/test.sh 1 $dateThe email I receive is the following.1 `dateWhy is test.sh not echoing the next day? When I pass $date to the command line it prints what I want it to as follows../test.sh 1 $date 1 2013-09-13Why is it different, and how do I instruct the crontab to pass into test.sh the next day?
Passing date to shell script from crontab
If we assume that the script that you want to run is located at/home/me/myscript.phpthen all you need to do is create a cron job that will run that script every minute.Several hosting companies have an interface (cPanel for instance) that will allow you to add a cron task easily. You can also add the cron task by editing the relevant cron job and adding:*/1 * * * * /usr/bin/php /home/me/myscript.php > /dev/null
I'm developing website that will send email back to user automatically when they registered to my website. I have searched from internet, most of them said that i have to used cron jobs; the big problem foo me now is about cron jobs. I don't how to write it and also how to execute it. Can anyone gives me some example about it?Thank in advance.
how to run php script automatically every minute without access to that page?
change5 * * * *to*/5 * * * *and it will run the cron job every 5 minutes
What i'm trying to do is to execute an URL once every 5 minutes, it's for an update to the database:so first i'm accessing the crontab:crontab -ethen i add to the existing list this line:5 * * * * /usr/bin/curl http://www.example.com/index.php/updateand i checked the DB after 5 minutes but there's no updating info. What is that i'm doing wrong? did i skip a step without knowing?Thanks in advance guys!
How to add an URL to a cron job on my server?
You need to supply theabsolutepath to the file in your script.Change the line:$test_file = "../xml_crontab.txt";to supply the absolute path toxml_crontab.txt.Remember thatcronisn't running in the same environment as you are and the script wouldn't be able to locate the file with relative pathname.
I'm trying to install this crontab:*/1 * * * * /usr/bin/php /var/www/vhosts/mydomain.net/httpdocs/administrator/makeXML.phpIn crontab there are others scripts installed. InmakeXML.phpI inserted a control to understand if crontab is executing:#!/bin/sh <?php $test_file = "../xml_crontab.txt"; $fp = fopen($test_file, 'a'); fwrite($fp, "Last xml generation: ".date("Y-m-d H:i:s")."\n"); fclose($fp); ... ?>I need to execute this script (makeXML.php) every one minute. What I'm doing wrong?
Crontab doesn't work
It is usually a good thing to use full path to commands in crontab. You should use the following.* * * * * /usr/bin/touch /tmp/chekifworks.txtThe environment in whichcronruns has a very limitedPATHvariable.It does not help to use a script (check for it being executable, btw), as the environment is transferred fromcronto the script, and still very limited.
Hello there all you awesome people of StackOverflow.I have a problem with something i have never tried before. Here is my situation.I ssh into my dedicated server as root. I run thecrontab -e, the crontab file is now open, I write in this simple line:* * * * * /usr/bin/touch /tmp/chekifworks.txtthen I save it and I get a message that a new crontab job is installed. Everything is great, except that it does absolutely nothing. But guess what! If I change it to this:* * * * * /root/script.shAnd the contents of /root/script.sh are simplytouch /tmp/testing.txtIt still does nothing.Output ofcrontab -l:* * * * * /usr/bin/touch /tmp/checkifworks.txt 0,5,10,15,20,25,30,35,40,45,50,55 * * * * /etc/webmin/status/monitor.pl @reboot /etc/init.d/shoutPlease, mighty gods of SO, help me out on this one, I will gladly provide any information you may need if you need it.UPDATE: I did achmod a+x /root/scrip.shstill no good.
Linux crontab ignores my entry