Response
stringlengths 8
2k
| Instruction
stringlengths 18
2k
| Prompt
stringlengths 14
160
|
---|---|---|
something like
0 0 * * * /path/to/mysqldump ... > /path/to/backup/mydata_$( date +"%Y_%m_%d" ).sql
should work.
Please read
man date
man 5 crontab
|
Hi i want to take database backup at daily mid night using cron job... and the name of database backup should append with current date... the format of backup file should be mydata_yyyy_mm_dd.sql ...
backup file should be placed in /root directory
|
Daily Database backup using Cron Job
|
You could use this class PHP-Parse-cron-strings-and-compute-schedules
It'll also compute the last scheduled run
|
I need to develop a task system that should be able to work on servers that doesn't support crontab.
I'm asking if there is any existing code that can take a cron string (e.g. '0 0,12 1 */2 *' and return the timestamp of the next scheduled run.
If such a code couldn't be found then how should I start with that?
|
PHP function that receive a cron string and return the next run timestamp
|
I've actually found a much better way of doing that by using ruby scripts.
This is how I did it:
First of all, I installed daemon
gem install daemons
Then I did:
require 'rubygems'
require 'daemons'
pwd = File.dirname(File.expand_path(__FILE__))
file = pwd + '/runner.rb'
Daemons.run_proc(
'my_project', # name of daemon
:log_output => true
) do
exec "ruby #{file}"
end
I then create a file called runner.rb, in which I can call my scripts such as:
require "/var/www/rails/my_project/config/environment"
Post.send('details....')
Daemons is a great gem!
|
Well, the title say it all. I have a ruby script I want running as a service (one I can start and stop) on my Linux box. I was able to find how to do it on Windows here
Some readings point to creating daemons or cron tasks.
I just need something simple I can call on my box's reboot, and can stop/start whenever I please. my script has an internal sleep call, and runs in "eternal loop"
thanks in advance
|
Ruby script as service
|
Something like:
crontab <<'EOF'
SHELL=/bin/bash
#min hr md mo wkday command
*/10 * * * * curl 'http://localhost:8983/solr/dataimport?command=full-import'
EOF
Use crontab -l to get a look at it afterwards. BUT, add an option to that curl command to put the output somewhere specific, since it might be run somewhere to which you don't have write access. Also, if curl is anywhere unusual, you may need to specify its full path, like /usr/bin/curl, or set the crontab PATH variable.
The quotes around EOF prevent substitution in the contents of the HEREIS document (everything between the <<EOF and EOF). HEREIS documents are a shell feature, not part ofcrontab`.
See man 5 crontab for a detailed breakdown of what goes in crontab files.
I usually keep a crontab -l0 file to edit with a special first line, and the execute bit set:
crontab -l1
This lets me edit my crontab -l2 and then just run it with:
crontab -l3
(I also usually have extensions on them to indicate which host they're for, like ~/.crontab.bigbox)
|
I want to run this statement:
curl 'http://localhost:8983/solr/dataimport?command=full-import'
every 10 minutes using CRON jobs.
How do I achieve this?
|
Run a curl command using CRON jobs
|
Use target tag to specify a backend in your cron.xml.
<?xml version="1.0" encoding="UTF-8"?>
<cronentries>
<cron>
<url>/long-task</url>
<description></description>
<schedule>every 30 minutes</schedule>
<target>name-of-the-backend</target>
</cron>
</cronentries>
|
I have a Dynamic Backend setup on GAE which I want to run using cron every 15mins. The problem is cron requires a url that begins with "/". While a backend URL uses the following format: http://backendname.yourapp.appspot.com.
I've read in other forums that you could use fetchurl to call your backend but I don't think that's the ideal way. Because that would require you to make your backend publicly accessible.
According to google's documentation:
http://code.google.com/appengine/docs/java/backends/overview.html#Public_and_Private_Backends
"Private backends can be accessed by application administrators, instances of the application, and by App Engine APIs and services (such as Task Queue tasks and Cron jobs) without any special configuration."
Has anybody got backends called by declaring it in cron.xml?
|
Execute Backends using Cron in Google App Engine (Java)
|
You may want to check your crontab syntax; crontab files in places like /etc/crontab require an extra username field, for example:
* * * * * root echo hi >> /root/test
This is documented (not very prominently) in crontab(5):
Jobs in /etc/cron.d/
The jobs in cron.d and /etc/crontab are system jobs, which are used usually for more
than one user, thus, additionally the username is needed....
|
Trying to run a cron job in a docker container.
HAve a supervisord properly configured
(I see cron -f in the ps -ef and if I kill it it respawns)
crontab file (for testing):
* * * * * echo hi >> /root/test
I tried putting it in /etc/cron.d/crontab /etc/crontab and in /var/spool/cron/crontabs/crontab
Nothing is working - I'm not getting anything in /root/test
Any ideas?
|
docker ubuntu cron -f is not working
|
10
It can be done much simpler
$oldApp = \Yii::$app;
new \yii\console\Application([
'id' => 'Command runner',
'basePath' => '@app',
'components' => [
'db' => $oldApp->db,
],
);
\Yii::$app->runAction('migrate/up', ['migrationPath' => '@yii/rbac/migrations/', 'interactive' => false]);
\Yii:$app = $oldApp;
Github LINK
Share
Improve this answer
Follow
edited Dec 31, 2016 at 12:00
answered Nov 1, 2016 at 7:20
Maksym SemenykhinMaksym Semenykhin
1,9451515 silver badges2626 bronze badges
Add a comment
|
|
I have created a console command in console/controllers with SuggestionController .
If i run command like php yii suggestions, its working.
I want to know how to execute console command from web without any extensions of yii2.
|
How to run console command in yii2 from web
|
If you have MySQL 5.1 you can use events.
http://dev.mysql.com/doc/refman/5.1/en/events.html
|
I would like to execute a procedure periodically, how to do that in MySQL?
|
Does MySQL have time-based triggers?
|
18
This is what javadoc says :
CronSequenceGenerator
the first field of the cron is for seconds.
Share
Improve this answer
Follow
edited Jun 29, 2016 at 8:16
Pirate X
3,08355 gold badges3636 silver badges6161 bronze badges
answered Jun 29, 2016 at 6:46
RoaslinRoaslin
18111 silver badge66 bronze badges
3
2
How to make it run every second ?
– GOXR3PLUS
Feb 11, 2019 at 9:00
11
Doc says "*/10 * * * * *" = every ten seconds. so the expression for every second would be "*/1 * * * * *"
– Farsee
May 26, 2020 at 18:35
I tried your suggestion, @Farsee and have to say that in my case the job runs every ten minutes, not seconds
– Arthur Eirich
Jan 21, 2022 at 11:32
Add a comment
|
|
it's strange, i setup corn as
@Scheduled(cron= "0 0/10 * * * ? ")
It did trigger every 10 minutes,
but the issue is task runs each second.
|
spring scheduled task run every second with cron(0 0/10 * * * ? )
|
9
You should enter these commands on Amazon Linux 2:
sudo systemctl start crond
sudo systemctl enable crond
Share
Improve this answer
Follow
edited Sep 17, 2021 at 22:32
answered Jul 10, 2019 at 22:32
Saeed IrSaeed Ir
2,15433 gold badges2222 silver badges2323 bronze badges
4
1
I'm getting: sudo systemctl start crond sudo: systemctl: command not found sudo systemctl start crond sudo: systemctl: command not found
– Gal Bracha
Jan 6, 2020 at 17:11
Maybe you're using Amazon Linux 1, it works on the latest Amazon Linux 2
– Saeed Ir
Jan 8, 2020 at 1:38
1
Tried the latest amazon linux 2
– Gal Bracha
Jan 8, 2020 at 14:39
1
Gal if you already ran sudo su - then you don't need to incluse sudo in the command.
– zeros-and-ones
Sep 18, 2021 at 5:18
Add a comment
|
|
I am hosting Tiny Tiny RSS site hosted on
Amazon Linux AMI
To update the feed automatically I have to run the following Cron job.
Reference
http://tt-rss.org/redmine/projects/tt-rss/wiki/UpdatingFeeds
*/30 * * * * /usr/bin/php /var/www/html/tt-rss/update.php --feeds --quiet
Here is the step I did:
sudo su
cd /etc
crontab -e
# add this line
*/30 * * * * /usr/bin/php /var/www/html/tt-rss/update.php --feeds --quiet
But I still got the message "Update Daemon is not running".
May I know, is this correct step for Cron job?
|
How to setup cron job on Amazon Linux AMI
|
from your working cmd-line, do
which lsof
which grep
which wc
which date
Take the full paths for each of these commands and add them into your shell script, producing something like
/bin/echo "Timestamp: `/bin/date +"%m-%d-%y %T"` Files: `/usr/sbin/lsof | /bin/grep app | /bin/wc -l`"
OR you can set a PATH var to include the missing values in your script, i.e.
PATH=/usr/sbin:${PATH}
Also unless you expect your script to be run from a true Bourne Shell environment, join the early 90's and use the form $( cmd ... ) for cmd-substitution, rather than backticks. The Ksh 93 book, published in 1995 remarks that backticks for command substitution are deprecated ;-)
IHTH
|
I have a small script do count open files on Linux an save results into a flat file. I intend to run it on Cron every minute to gather results later. Script follows:
/bin/echo "Timestamp: ` date +"%m-%d-%y %T"` Files: `lsof | grep app | wc -l`"
And the crontab is this:
*/1 * * * * /usr/local/monitor/appmon.sh >> /usr/local/monitor/app_stat.txt
If I run from shell ./script.sh it works well and outputs as:
Timestamp: 01-31-13 09:33:59 Files: 57
But on the Cron output is:
Timestamp: 01-31-13 09:33:59 Files: 0
Not sure if any permissions are needed or similar. I have tried with sudo on lsof without luck as well.
Any hints?
|
Script with lsof works well on shell not on cron
|
Short answer - it's not possible out of the box.
The value passed as the "cron expression" in the @Scheduled annotation is processed in ScheduledAnnotationBeanPostProcessor class using an instance of the StringValueResolver interface.
StringValueResolver has 3 implementations out of the box - for Placeholder (e.g. ${}), for Embedded values and for Static Strings - none of which can achieve what you're looking for.
If you have to avoid at all costs using the properties placeholder in the annotation, get rid of the annotation and construct everything programmatically. You can register tasks using ScheduledTaskRegistrar, which is what the @Scheduled annotation actually does.
I will suggest to use whatever is the simplest solution that works and passes the tests.
|
Is there a way to call a getter (or even a variable) from a propertyClass in Spring's @Scheduled cron configuration? The following doesn't compile:
@Scheduled(cron = propertyClass.getCronProperty()) or @Scheduled(cron = variable)
I would like to avoid grabbing the property directly:
@Scheduled(cron = "${cron.scheduling}")
|
Spring Boot @Scheduled cron
|
I don't think there's a performance indication in the monthly base just more of a suggestion of what to do with it. So i think you're ok with doing your cleanup using the events.
In the end the documentation suggets that the events are
Conceptually, this is similar to the idea of the Unix crontab (also known as a “cron job”) or the Windows Task Scheduler.
And the concept for those is that you can run a task every minute if you wish to do so.
On the second part of that question:
Serialize or spread it up. If you split them up into many events that will run at the same time you will create spikes of possibly very high cpu usage that might slow down the application while processing the events.
So either pack everything into one event so it runs in succession or spread the single events up so they execute on different times during the 15 minutes timeframe. Personally i think the first one is to be preferred, pack them up into a single event as then they are guaranteed to run in succession, even if a single one of them keeps running longer than usual.
The same goes for cronjobs. If you shedule 30 long-running exports at a single time your application is going to fail miserably during that timeslot (learned that the hard way).
|
In my web app I use two recurring events that "clean up" one of the tables in the database, both executed every 15 minutes or so.
My question is, could this lead to problems in performance in the future? Because I've read somewhere -I don't recall where exactly- that MySQL events are supposed to be scheduled to run once a month or so. Thing is, this same events keep the table in a pretty reduced size (as they delete records older than 15~ minutes), maybe this compensates the frequency of their execution, right?
Also, is it better to have one big MySQL event or many small ones if they are be called in the same frequency?
|
How expensive are MySQL events?
|
38
i would suggest creating your functionality as django-management-command and run it via crontab
if your command is send_newsletter then simply
0 0 * * * python /path/to/project/manage.py send_newsletter
and you don't need to take care of setting the settings module in this case/
Share
Improve this answer
Follow
answered Jul 8, 2010 at 3:08
AshokAshok
10.4k33 gold badges3737 silver badges2323 bronze badges
2
1
I'm trying this however the command fails with a DatabaseError: no such table.
– Raphael
Sep 15, 2011 at 18:50
3
I found out the problem: When using a sqlite3 database you must specify the full path to the database on the DATABASE settings
– Raphael
Sep 15, 2011 at 19:41
Add a comment
|
|
This question already has answers here:
Set up a scheduled job?
(26 answers)
Closed 10 years ago.
I need to create a function for sending newsletters everyday from crontab. I've found two ways of doing this on the internet :
First - file placed in the django project folder:
#! /usr/bin/env python
import sys
import os
from django.core.management import setup_environ
import settings
setup_environ(settings)
from django.core.mail import send_mail
from project.newsletter.models import Newsletter, Address
def main(argv=None):
if argv is None:
argv = sys.argv
newsletters = Newsletter.objects.filter(sent=False)
message = 'Your newsletter.'
adr = Address.objects.all()
for a in adr:
for n in newsletters:
send_mail('System report',message, a ,['[email protected]'])
if __name__ == '__main__':
main()
I'm not sure if it will work and I'm not sure how to run it. Let's say it's called run.py, so should I call it in cron with 0 0 * * * python /path/to/project/run.py
?
Second solution - create my send function anywhere (just like a normal django function), and then create a run.py script :
import sys
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
module_name = sys.argv[1]
function_name = ' '.join(sys.argv[2:])
exec('import %s' % module_name)
exec('%s.%s' % (module_name, function_name))
And then in cron call : 0 0 * * * python /path/to/project/run.py newsletter.views daily_job()
Which method will work, or which is better ?
|
Using crontab with django [duplicate]
|
28
Yes, but you can set an unlimited timeout by adding this to the top of your script:
set_time_limit(0);
Share
Improve this answer
Follow
answered May 18, 2011 at 2:32
cailinannecailinanne
8,36255 gold badges4141 silver badges4949 bronze badges
1
1
@john Flatness answer seems to be right. In my local XAMMP env I've tried setting the max_execution time to 10 seconds and ran the script via CLI it didn't produced any timeout issue.
– DavidG
Jul 5, 2022 at 9:25
Add a comment
|
|
Are PHP scripts run using the "php" command affected by the timeout limit? I plan to schedule php scripts using cron.
|
Are PHP scripts run using the "php" command affected by the timeout limit?
|
A solution without race condition or early exit problems is to use a lock file. The flock utility handles this very well and can be used like this:
flock -n /var/run/your.lockfile -c /your/script
It will return immediately with a non 0 status if the script is already running.
|
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Quick-and-dirty way to ensure only one instance of a shell script is running at a time
I've set up a cronjob to backup my folders properly which I am quite proud of. However I've found out, by looking at the results from the backups, that my backup script has been called more than once by Crontab, resulting in multiple backups running at the same time.
Is there any way I can ensure that a certain shell script to not run if the very same script already is executing?
|
Shell script: Ensure that script isn't executed if already running [duplicate]
|
Laravel scheduler works with commands, not with controller methods:
create command:
php artisan make:command PurchasePodcast
edit command:
namespace App\Console\Commands;
use Illuminate\Console\Command;
class PurchasePodcast extends Command
{
protected $name = 'purchase:podcast';
public function fire()
{
// do stuff here
}
}
add command to Console\Kernel.php:
protected $commands = [
'App\Console\Commands\PurchasePodcast',
];
use command in scheduler:
$schedule->command('purchase:podcast')->hourly();
|
My laravel version is 5.0.28, I build on cloud9, and I added this command to my cron:
#!/bin/bash
PATH=/usr/bin
* * * * * php /home/ubuntu/workspace/app/artisan scheduled:run 1>> /dev/null 2>&1
I added this code on my Kernel.php. I referenced this site: https://laravel-news.com/2014/11/laravel-5-scheduler/
<?php namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use App\Http\Controllers\ApiController;
class Kernel extends ConsoleKernel {
protected $commands = [
'App\Console\Commands\Inspire',
];
protected function schedule(Schedule $schedule)
{
$schedule->call('ApiController@test_job')->hourly();
}
}
I waited and it still didn't work, so I tried to use the command php artisan schedule:run, and I got: No scheduled commands are ready to run.
I searched and found this answer: Laravel 5 "Class does not exist" when using the scheduler
So I modified my code. Also, this code had no specified time, so I modified my cron to specify a time, but it still doesn't work. I have no more ideas. please help. Thanks.
code
$schedule->call(join('@', [ApiController::class, 'test_job']));
cron
0 0,3,6,9,12,15,18,21 * * * php /home/ubuntu/workspace/app/artisan schedule:run 1>> /dev/null 2>&1
30 1,4,7,10,13,16,19,22 * * * php /home/ubuntu/workspace/app/artisan schedule:run 1>> /dev/null 2>&1
|
Laravel 5 schedule not working
|
If you're running it manually and it works you're probably in a different shell environment than cron is executing in. Since you mention you're on Ubuntu, the cron jobs probably execute under /bin/sh, and you're manually running them under /bin/bash if you haven't changed anything.
You can debug your environment problems or you can change the shell that your job runs under.
To debug, There are several ways to figure out what shell your cron jobs are using. It can be defined in
/etc/crontab
or you can make a cron job to dump your shell and environment information, as has been mentioned in this SO answer: How to simulate the environment cron executes a script with?
To switch to that shell and see the actual errors causing your job to fail, do
sudo su
env -i <path to shell> (e.g. /bin/sh)
Then running your script you should see what the errors are and be able to fix them (rubygems?).
Option 2 is to switch shells. You can always try something like:
0 3 * * * /bin/bash -c '~/Downloader/download.rb > ~/Downloader/output.log 2>&1'
To force your job into bash. That might also clear things up.
|
I have a ruby script that connects to an Amazon S3 bucket and downloads the latest production backup. I have tested the script (which is very simple) and it works fine.
However, when I schedule this script to be run as a cron job it seems to fail when it loads the Amazon (aws-s3) gem.
The first few lines of my script looks like this:
#!/usr/bin/env ruby
require 'aws/s3'
As I said, when I run this script manually, it works fine. When I run it via a scheduled cron job, it fails when it tries to load the gem:
`require': no such file to load -- aws/s3 (LoadError)
The crontab for this script looks like this:
0 3 * * * ~/Downloader/download.rb > ~/Downloader/output.log 2>&1
I originally thought it might be because cron is running as a different user, but when I do a 'whoami' at the start of my ruby script it tells me it's running as the same user I always use.
I have also done a bundle init and added the gem to my gemfile, but this doesn't seem to have any affect.
Why does cron fail to load the gem? I am running Ubuntu.
|
Cron job can't load gem
|
Hmmm, interesting problem.
If you're going to really validate it, regex isn't going to be enough, you'll have to actually parse the entry and validate each of the scheduling bits. That's because each bit can be a number, a month/day of the week string, a range (2-7), a set (3, 4, Saturday), a Vixie cron-style shortcut (60/5) or any combination of the above -- any single regex approach is going to get very hairy, fast.
Just using the crontab program of Vixie cron to validate isn't sufficient, because it actually doesn't validate completely! I can get crontab to accept all sorts of illegal things.
Dave Taylor's Wicked Cool Shell Scripts (Google books link) has a sh script that does partial validation, I found the discussion interesting. You might also use or adapt the code.
I also turned up links to two PHP classes that do what you say (whose quality I haven't evaluated):
http://www.phpclasses.org/browse/package/1189.html
http://www.phpclasses.org/browse/package/1985.html
Another approach (depending on what your app needs to do) might be to have PHP construct the crontab entry programatically and insert it, so you know it's always valid, rather than try to validate an untrusted string. Then you would just need to make a "build a crontab entry" UI, which could be simple if you don't need really complicated scheduling combinations.
|
What is the best way to validate a crontab entry with PHP? Should I be using a regex, or an external library? I've got a PHP script that adds/removes entries from a crontab file, but want to have some way to verify that the time interval portion is in a valid format.
|
Validating Crontab Entries with PHP
|
The solution is:
apk add --update busybox-suid
|
I faced an issue with crontab in alpine under my non-root account.
bash-4.3$ crontab -e
crontab: must be suid to work properly
Here is the output of id command:
bash-4.3$ id
uid=41532(fred) gid=41532(fred) groups=41532(fred),41532(fred)
Btw everything works for root account.
|
Failed to edit crontab (linux Alpine)
|
I don't know how people are uploading content to this folder, but you might want to use something lower-tech than monitoring the directory with inotify.
If the protocol is FTP and you have access to your FTP server's log, I suggest tailing that log to watch for successful uploads. This sort of event-triggered approach will be faster, more reliable, and less load than a polling approach with traditional cron, and more portable and easier to debug than something using inotify.
The way you handle this will of course depend on your FTP server. I have one running vsftpd whose logs include lines like this:
Fri May 25 07:36:02 2012 [pid 94378] [joe] OK LOGIN: Client "10.8.7.16"
Fri May 25 07:36:12 2012 [pid 94380] [joe] OK UPLOAD: Client "10.8.7.16", "/path/to/file.zip", 8395136 bytes, 845.75Kbyte/sec
Fri May 25 07:36:12 2012 [pid 94380] [joe] OK CHMOD: Client "10.8.7.16", "/path/to/file.zip 644"
The UPLOAD line only gets added when vsftpd has successfully saved the file. You could parse this in a shell script like this:
#!/bin/sh
tail -F /var/log/vsftpd.log | while read line; do
if echo "$line" | grep -q 'OK UPLOAD:'; then
filename=$(echo "$line" | cut -d, -f2)
if [ -s "$filename" ]; then
# do something with $filename
fi
fi
done
If you're using an HTTP upload tool, see if that tool has a text log file it uses to record incoming files. If it doesn't consider adding some sort of logger function to it, so it'll produce logs that you can tail.
|
I have a folder named images on my linux box.
This folder is connected to a website and the admin of the site has the ability to add pictures to this site. However, when a picture is added, I want a command to run resizing all of the pictures a directory.
In short, I want to know how I can make the server run a specific command when a new file is added to a specific location.
|
Run a shell command when a file is added
|
You can either use curl via backticks
my $curl=`curl http://whatever`
or you can use WWW::Curl.
|
I have a very simple task. I have a crontab that will run a script every hour. The script is meant to simply process a URL.
This is what I have. It doesn't work. I get a syntax error.
#!/usr/bin/perl
curl http://domain.com/page.html;
I haven't worked in Perl in years and wasn't very adept when I did.
SOLUTION
Thanks, Alex for pointing me to the correct path!
crontab
*/30 * * * * curl http://domain.com/path.html
|
How do I write a Perl script to use curl to process a URL?
|
Just adding on from the comment that says create it yourself.
Here is an example: Prompt the user for the values and pass them into the following method, the Javadoc explains what is allowed in which value (taken from http://en.wikipedia.org/wiki/Cron#Format).
This is untested and doesn't validate any of the input strings, but I'm sure you can do that.
/**
* Generate a CRON expression is a string comprising 6 or 7 fields separated by white space.
*
* @param seconds mandatory = yes. allowed values = {@code 0-59 * / , -}
* @param minutes mandatory = yes. allowed values = {@code 0-59 * / , -}
* @param hours mandatory = yes. allowed values = {@code 0-23 * / , -}
* @param dayOfMonth mandatory = yes. allowed values = {@code 1-31 * / , - ? L W}
* @param month mandatory = yes. allowed values = {@code 1-12 or JAN-DEC * / , -}
* @param dayOfWeek mandatory = yes. allowed values = {@code 0-6 or SUN-SAT * / , - ? L #}
* @param year mandatory = no. allowed values = {@code 1970–2099 * / , -}
* @return a CRON Formatted String.
*/
private static String generateCronExpression(final String seconds, final String minutes, final String hours,
final String dayOfMonth,
final String month, final String dayOfWeek, final String year)
{
return String.format("%1$s %2$s %3$s %4$s %5$s %6$s %7$s", seconds, minutes, hours, dayOfMonth, month, dayOfWeek, year);
}
Cron Format Information taken from here: http://en.wikipedia.org/wiki/Cron#Format
|
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I need a Java code to create a cron expression based on user inputs.
User inputs are Time, frequency and number of executions.
|
Is there any Java code for creating Cron Expression? [closed]
|
After seeing the comment by Gomes, I checked and it seems both are valid in my system:
$ /usr/bin/dotnet --version
2.1.400
$ /usr/share/dotnet/dotnet --version
2.1.400
I did a bit more research and it appears that the usual way to find this in many unix dialects (as per https://kb.iu.edu/d/acec) is with the help of whereis command:
$ whereis dotnet
dotnet: /usr/bin/dotnet /usr/share/dotnet /usr/share/man/man1/dotnet.1.gz
But with further scrutiny, I could see that /usr/bin/dotnet is just a symlink to /share/dotnet/dotnet:
/usr/bin$ ll dotnet
lrwxrwxrwx 1 root root 22 Jun 29 17:48 dotnet -> ../share/dotnet/dotnet*
And that page also shows how to see which one the operating system uses when running a command you type in the terminal, which command:
$ which dotnet
/usr/bin/dotnet
|
I'm trying to use dotnet (.NET Core) with cron jobs, but it seems the path variable for dotnet doesn't exist in the scope of cron. I'd like to add the path to cron, but I need to know where dotnet is actually installed to from a typical Ubuntu installation. Also knowing how to add the path variable to cron would be helpful also, but I think I can figure that out once I have the dotnet installation directory.
|
Where is the dotnet runtime installed to on Ubuntu?
|
I strongly recommend to use CLI for such requirement.
Create a ConsoleController with an updateAction() inside the application module.
Add a console route to your application module's module.config.php:
array(
'router' => array(
'routes' => array(
...
)
),
'console' => array(
'router' => array(
'routes' => array(
'cronroute' => array(
'options' => array(
'route' => 'updateproducts',
'defaults' => array(
'controller' => 'Application\Controller\Console',
'action' => 'update'
)
)
)
)
)
)
);
Now open the terminal and
$ cd /path/to/your/project
$ php public/index.php updateproducts
Thats all. Hope it helps.
|
I have application built in Zend Framework 2. I would like to set cron job for updating my products. I know scripts such as this should be run from outside of public folder, but unfortunately my script in cron needs to use framework files.
How can I do this?
The only way I figured out is to run script from outside of public folder then add some hash or password and redirect to
www.domain.com/cron/test
So I will have all framework functionality.
Will it be secure? Maybe there is a other way?
|
How to run cron job with zend framework 2
|
Just a guess, but you don't
Best hack off the top of my head: write a script to track the last time it was run, and conditionally run it if it was more than 25 hours ago.
Cron that driver script to run every hour.
|
How do I set up a cronjob that runs every 25th hour?
|
Cronjob every 25 hours?
|
* means every possible value in the field. ? means you don't care about the value. It's used when you have two fields that may contradict each other. The common example being the day of month and day of week fields. Consider, for example a cron specification for running at 10AM on the first day of every month:
0 0 10 1 * ? *
Now let's break it down:
Seconds: 0 - we want it to run on 10:00:00
Minutes: 0 - we want it to run on 10:00:00
Hours: 10 - we want it to run on 10:00:00
Day of month: 1 - we want it to run of the 1st of every month
Month: * - we want it to run on every month (e.g., January 1st, February 1st, etc.)
Day of week: ? - we don't care about the day of week. The cron should run on the 1st of every month, regardless of whether it's a Sunday, a Monday, etc.
Year: * - we want it to run on every year
|
It appears to me that both mean "any of the available values". What exactly in the difference between them?
|
Cron Expression: What exactly is the difference between ? and * in a cron expression?
|
Your cron will run every minute at 6 o'clock, because of that asterisk.
Cron format:
* * * * * *
| | | | | |
| | | | | +-- Year (range: 1900-3000)
| | | | +---- Day of the Week (range: 1-7, 1 standing for Monday)
| | | +------ Month of the Year (range: 1-12)
| | +-------- Day of the Month (range: 1-31)
| +---------- Hour (range: 0-23)
+------------ Minute (range: 0-59)
Any of these 6 fields may be an asterisk (*).
This would mean the entire range of possible values, i.e. each minute, each hour, etc.
You should put minute 0 because you need to run it just once (at 06:00).
0 6 * * *
|
how to make cron job every day at 6 O'clock by Cpanel ?
I added cron job by my cpanel as this picture
https://i.stack.imgur.com/5esAq.jpg
But the script work more one time in the day , I need to know the error in cron or in my script .
|
how to make cron job every day at 6 O'clock by Cpanel
|
You might want to check out Later.js which can parse a Cron expression and calculate the next occurrences.
var schedule = cronParser().parse('* */5 * * * *', true);
var results = later(60).get(schedule, 100, startDate, endDate);
|
Does anyone know of any existing solutions using javascript that can parse a crontab and return all datetime instances between a given start and end date?
ie if i have 0 * * * *, start 24/10/2011 16:00 and end 24/10/2011 19:00 then it will return:
24/10/2011 16:00,
24/10/2011 17:00,
24/10/2011 18:00
|
Getting datetimes from cron format using javascript
|
as the documentation states http://laravel.com/docs/5.1/queues, first you need to setup the driver - i would go for database in the beginning :
php artisan queue:table
php artisan migrate
then create the Job that you want to add to the queue
<?php
namespace App\Jobs;
use App\User;
use App\Jobs\Job;
use Illuminate\Contracts\Mail\Mailer;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Contracts\Queue\ShouldQueue;
class SendEmail extends Job implements SelfHandling, ShouldQueue
{
use InteractsWithQueue, SerializesModels;
protected $user;
public function __construct(User $user)
{
$this->user = $user;
}
public function handle(Mailer $mailer)
{
$mailer->send('emails.hello', ['user' => $this->user], function ($m) {
//
});
}
}
then in the Controller dispatch the job
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use App\Jobs\SendReminderEmail;
use App\Http\Controllers\Controller;
class UserController extends Controller
{
/**
* Send a reminder e-mail to a given user.
*
* @param Request $request
* @param int $id
* @return Response
*/
public function sendReminderEmail(Request $request, $id)
{
$user = User::findOrFail($id);
$sendEmailJob = new SendEmail($user);
// or if you want a specific queue
$sendEmailJob = (new SendEmail($user))->onQueue('emails');
// or if you want to delay it
$sendEmailJob = (new SendEmail($user))->delay(30); // seconds
$this->dispatch($sendEmailJob);
}
}
For that to work, you need to be running the Queue Listener:
php artisan queue:listen
Does that answer?
|
I am developing a website in Laravel 5.0 and hosted in Windows Server2012.
I am stuck at a problem which is I am calling a function B in controller from another function A and I want that the function A which calls the another function B does not wait for the completion of function B . And Function B gets completes in the background and independent form user termination of page and function A return .
I have searched this and found that this can be implemented through cron like jobs in windows, pcntl_fork() and Queue functionality in laravel. I am beginner in all this.
Please help! thanks in advance.
|
How to make function run in background in laravel
|
I found the solution: changing the visibility of the class defining the job (Printer) to public will make it possible to Quartz to access it and run it.
public class Printer implements Job { // just add 'public'!
public Printer() {
System.out.println("created printer");
}
@Override
public void execute(JobExecutionContext context)
throws JobExecutionException {
System.out.println("hi" + context.getFireTime());
}
}
That's understandable, since it's only possible to pass a <? extends Job>.class
to the scheduler (bloody hell, why??) and not - for example - anonymous objects.
Having that said, I find really upsetting the way Quartz silently fails firing jobs without a single error message.
|
This should be pretty straight forward, but I see no job being executed. I have a breakpoint on the execute() method of the task, no thread gets there ever.
I'm not getting what's wrong.
the Job
class Printer implements Job{
public Printer(){
System.out.println("created printer");
}
@Override
public void execute(JobExecutionContext context)
throws JobExecutionException {
System.out.println("hi" + context.getFireTime());
}
}
The main class
class MyClass {
public static void main(String[] args) throws Throwable {
Scheduler s = StdSchedulerFactory.getDefaultScheduler();
JobDetail job = newJob(Printer.class).build();
CronTrigger trigger =
newTrigger()
.withIdentity("a", "t")
.withSchedule(cronSchedule("0/5 * * * * ?").inTimeZone(TimeZone.getDefault()))
.forJob(job).build();
s.scheduleJob(job, trigger);
// This prints the right date!
System.out.println(trigger.getNextFireTime());
s.start();
}
}
EDIT: I discovered I didn't have the quartz.property file, so there was the possibility the threadpool for quartz was not ever created. Therefore as read in documentation, I replaced the code using StdSchedulerFactory with the following:
DirectSchedulerFactory.getInstance().createVolatileScheduler(10);
Scheduler s = DirectSchedulerFactory.getInstance().getScheduler();
Guess what? No luck still. Same identical effect. Application keeps staying alive, firing not trigger.
|
Quartz not firing simple trigger
|
Oops...I was missing the newline character at the end of the cron job. That seems to have fixed it.
|
I'm trying to set up an automated svn commit to run semi-hourly under mac os 10.6, but the crontabs i'm adding to cron don't seem to be valid and/or don't seem to even be looked at by cron. For testing i made a simple crontab and script:
Crontab:
*/2 * * * * /Users/username/crontest
where username is replaced with my system username, thus pointing to my home directory (and yes, those really are tabs between each value - they aren't faithfully reproduced in the code section)
I'm running a crontab -r first, then running crontab .mycrontab that contains the above line. crontab -l spits out the line above, and running ps -A | grep cron shows /usr/sbin/cron running, which I assume is the cron daemon under mac os x. The /Users/username/crontest script is simply appending a line of text to a text file, as such:
echo "hi" >> /Users/username/crontest.txt
What gives? I'm stumped.
|
cron jobs under mac os 10.6 snow leopard
|
MySQL events offer an alternative to scheduled tasks and cron jobs.
Events can be used to create backups, delete stale records, aggregate data for reports, and so on. Unlike standard triggers which execute given a certain condition, an event is an object that is triggered by the passage of time and is sometimes referred to as a temporal trigger.
Refer below link explained everything here :
http://phpmaster.com/working-with-mysql-events/
|
What is a "MySQL event"? What is its purpose? How is it different from a "job scheduler"?
Many posts on SO, and the MySQL documentation, describe how to implement MySQL events, but I am just interested in their purpose.
|
What is a "MySQL event"?
|
You get this error because you execute this script like ./script.php. In order to make sure the PHP script understand and run properly, you have to include #!/usr/bin/php at the top of your script.
Example:
#!/usr/bin/php
<?php
echo 'Enter a number:';
$line = trim(fgets(STDIN));
var_dump($line);
If PHP is installed in the /usr/bin folder. If not, you can verify using the locate php command and then use the right path.
Or the other alternative will be
php /path/to/script.php
|
I am trying to build a PHP script to process data manually to later convert it to a cronjob. This script also gets data from MySQL and a third-party SOAP interface. When I try to run it from the command line I have an error and the script does not run.
It shows:
./test.php: line 1: ?php: No such file or directory
Enter a number:
./test.php: line 5: syntax error near unexpected token `('
./test.php: line 5: `$line = trim(fgets(STDIN));'
Here's what I have in my script:
echo 'Enter a number: ';
$line = trim(fgets(STDIN));
var_dump($line);
I know this script works. What is wrong?
|
Command-line script PHP does not run
|
12
Each RUN command creates a temporary container on your build host using the resulting image from the prior step and the RUN arg as the container's command. A container only runs as long as the command you execute is active, so if it's a command that launches a background daemon like you've done, the container exits when the command returns, not when the background daemon exits.
The RUN command is used to build up your image which is the layered filesystem and various meta data that tells docker how to use that filesystem (environment variables, entrypoint and/or command to run by default, etc). It is very different from a CMD which tells docker what to run when that image is turned into a container. So for a process that you need to have running in the container, that needs to be part of your CMD or ENTRYPOINT since running processes from RUN are not part of a static filesystem image.
I'd also follow the advice of others and copy an already existing image with cron inside, no need to reinvent this wheel. You may want to use a tool like supervisord to run cron and your application together if you need to have multiple processes inside your container. Though when possible, you should work out how to break this into multiple containers that can be independently updated.
Share
Improve this answer
Follow
answered Sep 15, 2017 at 11:49
BMitchBMitch
246k4444 gold badges509509 silver badges473473 bronze badges
Add a comment
|
|
When I start the cron service within the running Docker container with
service cron start
it works. But the line
RUN service cron start
within the Dockerfile seems not to have an effect. Why?
Alternatives
I thought about simply changing my CMD to something like CMD ["startup.sh"] which first runs service cron start and then run.py (a Python webserver). But I want the web server not to run as root and thus service cron start would fail.
|
Why doesn't "service cron start" work within the Docker file?
|
If you create a cron with:
*/30 * * * * /command/to/execute
it is the same as:
0,30 * * * * /command/to/execute
which means it will run twice; once on the hour and then 30 mins past the hour.
It doesn't matter what time you create it.
Another example:
*/29 * * * * /command/to/execute
is the same as:
0,29,58 * * * * /command/to/execute
So the cron will run at 00:00, 00:29, 00:58, 01:00, 01:29, 01:58 and so on.
(You can think of / as division. Every minute (*) is divided by 29...)
|
I'm setting up a cronjob to run every 30 minutes on a Linux server.
When does the 30 minute countdown start? Is it counted from the minute I created the cronjob or is it based on a preset 30 minute schedule?
For example:
If I create a cronjob at 9:32, set to run every 30 minutes, will it run at 9:32, 10:02, 10:32, 11:02...
Or is there a predetermined run time such as it's first run would be 10:00 then 10:30, 11:00, 11:30...
|
Does cronjob timing start from the moment it's created or is it preset?
|
10
An alternative solution could be by running php artisan schedule:run with supervisor. In my case I have a schedule-run.conf in [project root]/.docker/php/workers:
[program:schedule-run]
process_name=%(program_name)s_%(process_num)02d
command=/bin/bash -c "while [ true ]; do (php /var/www/html/artisan
schedule:run --verbose --no-interaction &); sleep 60; done"
autostart=true
autorestart=true
user=root
numprocs=1
redirect_stderr=true
stdout_logfile=/var/www/html/storage/logs/schedule.log
stopwaitsecs=60
replace your apt-get install -y cron by apt-get install -y supervisor
add ADD .docker/php/workers /etc/supervisor/conf.d and CMD ["/usr/bin/supervisord"] to your Dockerfile.
Share
Improve this answer
Follow
answered Mar 26, 2021 at 19:04
Rafael AffonsoRafael Affonso
30144 silver badges77 bronze badges
2
Nice one! You usually need supervisor anyway for the queue workers. But i would not run this as root.
– zidanex
Jul 8, 2021 at 20:50
You're right about the use of root. I would use another user in a production scenario, like www or www-data.
– Rafael Affonso
Jul 14, 2021 at 18:35
Add a comment
|
|
I have a container with for my laravel app with php:7.0.4-fpm as base image.
This is my dockerfile :
FROM php:7.0.4-fpm
RUN apt-get update && apt-get install -y cron nano libmcrypt-dev \
mysql-client libmagickwand-dev --no-install-recommends \
&& pecl install imagick \
&& docker-php-ext-enable imagick \
&& docker-php-ext-install mcrypt pdo_mysql
COPY . /var/www
ADD crontab /etc/cron.d/laravel-cron
RUN chmod 0644 /etc/cron.d/laravel-cron
RUN touch /var/log/cron.log
RUN /usr/bin/crontab /etc/cron.d/laravel-cron
RUN cron
Cron is not running, I have to ssh in the container to launch it.
When I start it manually it works for som simple things like echoing a text every minute. But not for the php artisan schedule:run command. In the log I see :
Running scheduled command: '/usr/local/bin/php' 'artisan'
errors:insert > '/dev/null' 2>&1
errors:insert is the name of my task, but nothing is update in the website.
That's strange because when I run php artisan schedule:run command manually it works on the website.
So my question is : How to make cron work on a docker container to execute the php artisan schedule:run command ? Preferably written in a dockerfile and not manually via ssh.
I also have a strange message from the container :
ALERT: oops, unknown child (5094) exited with code 1.
Please open a bug report (https://bugs.php.net).
|
cron on a docker container for laravel not working
|
I suspect (edit: I'm pretty sure by now) that it doesn't do what you want: fields are separate, and */45 for minutes is nothing more than 0,45. I would use the following three entries if */45 doesn't do the job:
0,45 0-23/3 * * *
30 1-23/3 * * *
15 2-23/3 * * *
If you take a look at entry.c file in vixie cron sources, you'll notice that each field of each entry is parsed by get_list and represented as bitmaps of allowed values for that field. That almost precludes any "smart" interpretation, as the distinction of */45 and 0,45 is lost at this stage... but there is a MIN_STAR flag, set at the presence of * in minutes (including 0,450). So we take a look at 0,451, a single place where 0,452 is examined, to learn it's unrelated to our problem. Now we know for sure that 0,453 means "every 45th minute of every hour": 0:00, 0:45, 1:00, 1:45 and so on.
There were two answers here confidently stating the opposite, quoting an unfortunate passage in the manual:
Steps are also permitted after an asterisk, so if you want to say
"every two hours", just use "*/2"
We are lucky to have a 24 hour day, containing even number of hours, making "every two hours from 0:00, each day" and "every two hours generally" indistinguishable. Too bad that the manual didn't go far enough to document non-trivial cases, making the impression that 0,454 means every 22 hours. It does not. Star with a step is just a shorthand for a list of values in the field where it's used; it doesn't interact with other fields.
|
Am willing to run a script every 45 minute (not the :45th minute of every hour)
e.g. 10:00, 10:45, 11:30, 12:15, and so on.
*/45 * * * *
Am not sure this is the correct expression.
|
Is the following cron expression means every 45 minutes?
|
10
cronTrigger.getExpressionSummary()
Example:
CronTrigger t = new CronTrigger();
t.setCronExpression("0 30 10-13 ? * WED,FRI");
System.out.println(""+t.getExpressionSummary());
Output:
seconds: 0
minutes: 30
hours: 10,11,12,13
daysOfMonth: ?
months: *
daysOfWeek: 4,6
lastdayOfWeek: false
nearestWeekday: false
NthDayOfWeek: 0
lastdayOfMonth: false
years: *
Api Java Doc
Share
Improve this answer
Follow
edited Dec 17, 2010 at 10:02
answered Dec 17, 2010 at 9:52
Jigar JoshiJigar Joshi
239k4242 gold badges404404 silver badges441441 bronze badges
8
1
Ok, that seems to be kind of a dump for the developer. Thx, for showing me the class which is a good way to hold the string as object. I'm investigating there a little more. However, I can't present this dump to an Android user.
– OneWorld
Dec 17, 2010 at 11:20
I can't present this dump to an Android user. didn't get this point, you want a lib specific to android ?
– Jigar Joshi
Dec 17, 2010 at 11:22
1
No. But imagine you see this dump on a small smartphone screen.
– OneWorld
Dec 17, 2010 at 12:37
You can accommodate this dump scrollable table view, I don't know much about andriod programming otherwise I would have suggested you the component
– Jigar Joshi
Dec 17, 2010 at 13:00
1
My designer is going to kill me if I do that ;) This output is not human readable or at least "customer readable", "designer readable" ;)
– OneWorld
Dec 17, 2010 at 14:32
|
Show 3 more comments
|
Closed. This question is seeking recommendations for software libraries, tutorials, tools, books, or other off-site resources. It does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for software libraries, tutorials, tools, books, or other off-site resources. You can edit the question so it can be answered with facts and citations.
Closed 6 years ago.
Improve this question
I am looking for a parser that converts a cron expression like 45 17 7 6 * * into Every year, on June 7th at 17:45 The parser should be adjustable to other languages. German for the first step.
Is there a library for a
JAVA based Android project
Objective-C based Iphone project.
See here for the usecase.
|
Convert cron expression into nice description strings? Is there a library for JAVA and Objective-C? [closed]
|
You may consider Quartz (a java-based solution), that can take advantage of Date build in the appropriate TimeZone.
|
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 10 years ago.
Improve this question
Does anyone know of a good alternative to cron? I would like something that can be run with different time zones.
|
alternative to cron? [closed]
|
Apples and oranges. cron is a Unix service. IIS is a web server. Just as cron is not included in Apache or nginx, there is no sense in which IIS contains a scheduler. However, you can use schtasks.exe in a similar way you can use cron on Unix.
You might find more ideas in this question.
|
I'm developing an ASP.NET web application. There is some functionality I need to trigger every 10 minutes. So currently I'm considering a 'scheduled task' or to create a Windows service to call the URL.
But I remember once I did the same thing in a PHP web hosting space, using a cron job.
So is there anything like cron jobs in IIS?
Note: I'm not expecting to use 3rd-party online scheduler services.
|
Is there something like cron jobs in IIS?
|
UNIX cron's API is the filesystem. There is a crontab command for installing/editing user crontabs. The main reason for the crontab command is to enforce security restrictions on users (e.g., /etc/cron.allow and /etc/cron.deny).
System cron tabs are just files placed in /etc/cron.d (and cron.daily/weekly/monthly). No special care is needed; just drop the file in place. To quote the top of /etc/crontab:
# /etc/crontab: system-wide crontab
# Unlike any other crontab you don't have to run the `crontab'
# command to install the new version when you edit this file
# and files in /etc/cron.d. These files also have username fields,
# that none of the other crontabs do.
The format is the same as user crontabs, documented in crontab(5), but with a user field right before the command. Where SPACE means whitespace (one or more) and both 0 and 7 mean Sunday:
minute SPACE hour SPACE day-of-month SPACES month SPACE day-of-week SPACE user SPACE command
Using normal POSIX file access won't step on cron's toes. Remember, rename will always have the target name pointing to either the old or new file, never to nothing. So you can write the file to a new name and then rename it over top your old one.
Many programming languages have APIs to help with writing crontabs. For example, CPAN (Perl) has several.
|
Is there such a thing as a Cron API?
I mean, is there a programmatic way of adding/removing Cron jobs without stepping onto Cron's toes?
|
Cron API: is there such a thing?
|
3
A quick google turns up a few decent results:
http://www.bitfolge.de/pseudocron-en.htm
http://www.phpclasses.org/browse/package/4140.html
http://www.hotscripts.com/Detailed/61437.html
Really, though, if you're on any decent shared hosting package you should have access to some sort of task scheduler be it Windows' Task Scheduler or cron under *nix. I know DreamHost allows user level crontabs, at least.
Share
Improve this answer
Follow
edited Feb 27, 2020 at 23:30
Dharman♦
31.9k2525 gold badges9191 silver badges139139 bronze badges
answered Nov 25, 2008 at 18:24
willasaywhatwillasaywhat
2,3742020 silver badges2323 bronze badges
2
I'm fine using cron. It is just that cron alone does not give most of the functionality listed. Really, it only gives the first item.
– Tim
Nov 25, 2008 at 18:39
quick google turns up, first this answer. could you imagine 10 years ago that someone quickl google a question and find you. Like your sarcasm turn out a real answer.
– nerkn
Feb 16, 2018 at 22:27
Add a comment
|
|
Is there a full featured, job scheduling package available for PHP? I'm looking for the PHP equivalent to Java's Quartz. I'm fine having things triggered externally from cron to drive the system. The functionality I'd be looking for:
Ability to register task (class/method) to be called at given intervals.
Ability to specify whether a given task can be run multiple times (potentially long running methods should not be run multiple times in certain cases).
All registered entries/methods could be run in parallel (jobs are backgrounded so that they do not block other timed tasks).
Ability to set a timeout for a given task.
Ability to update job control dynamically, so for instance you could disable some tasks or change their frequency without code changes.
I know it is a lot to ask, but it seems like a useful batch of features and I thought someone might have put together some portion of them.
If this or some portion of this does not already exist, any pointers to putting one together or an open source project that has a reasonably featureful implementation of some subset of these?
|
Timed Tasks (cron-like) in PHP
|
You will need to store data about jobs somewhere. On Heroku, you don't have any informations or warranty about your code being running only once and all the time (because of cycling)
You may use a project like this on (but not very used) : https://github.com/amitree/delayed_job_recurring
Or depending on your need you could create a scheduler or process which schedule jobs for the next 24 hours and is run every 4 hours in order to be sure your jobs will be scheduled. And hope that the heroku scheduler will work at least once every 24 hours.
And have at least 2 worker processing the jobs.
|
I'm building a Heroku app that relies on scheduled jobs. We were previously using Heroku Scheduler but clock processes seem more flexible and robust. So now we're using a clock process to enqueue background jobs at specific times/intervals.
Heroku's docs mention that clock dynos, as with all dynos, are restarted at least once per day--and this incurs the risk of a clock process skipping a scheduled job: "Since dynos are restarted at least once a day some logic will need to exist on startup of the clock process to ensure that a job interval wasn’t skipped during the dyno restart." (See https://devcenter.heroku.com/articles/scheduled-jobs-custom-clock-processes)
What are some recommended ways to ensure that scheduled jobs aren't skipped, and to re-enqueue any jobs that were missed?
One possible way is to create a database record whenever a job is run/enqueued, and to check for the presence of expected records at regular intervals within the clock job. The biggest downside to this is that if there's a systemic problem with the clock dyno that causes it to be down for a significant period of time, then I can't do the polling every X hours to ensure that scheduled jobs were successfully run, since that polling happens within the clock dyno.
How have you dealt with the issue of clock dyno resiliency?
Thanks!
|
Heroku clock process: how to ensure jobs weren't skipped?
|
Just create another cron:
0 3 * * * find $HOME/db_backups -name "db_name*.sql" -mtime +30 -exec rm {} \; >> $HOME/db_backups/purge.log 2>&1
It will find all backups older than 30 days and delete them.
|
I use the following crontab record in order to daily backup my DB:
0 2 * * * MYSQL_PWD=password mysqldump -u user db_name > $HOME/db_backups/db_name-$(date +\%Y-\%m-\%d-\%H-\%M).sql 2>> $HOME/db_backups/cron.log
I want to add another crontab record that will delete the DB dumps that are older then one month.
Any thoughts?
|
deleting old files using crontab
|
@reboot doesn't guarantee that the job will never be run. It will actually be run always when your system is booted/rebooted and it may happen. It will be also run each time when cron daemon is restarted so you need to rely on that "typically it should not happen" on your system...
There are far more certain ways to ensure that a CronJob will never be run:
On Kubernetes level by suspending a job by setting its .spec.suspend field to true
You can easily set it using patch:
kubectl patch cronjobs <job-name> -p '{"spec" : {"suspend" : true }}'
On Cron level. Use a trick based on fact that crontab syntax is not strictly validated and set a date that you can be sure will never happen like 31th of February. Cron will accept that as it doesn't check day of the month in relation to value set in a month field. It just requires that you put valid numbers in both fields (1-31 and 1-12 respectively). You can set it to something like:
* * 31 2 *
which for Cron is perfectly valid value but we know that such a date is impossible and it will never happen.
|
Here is part of my CronJob spec:
kind: CronJob
spec:
schedule: #{service.schedule}
For a specific environment a cron job is set up, but I never want it to run. Can I write some value into schedule: that will cause it to never run?
I haven't found any documentation for all supported syntax, but I am hoping for something like:
@never or @InABillionYears
|
Schedule cron job to never happen?
|
Here's how we implemented this for the DjangoDose live feed during DjangoCon (note: this is a hackjob, we wrote it in 1 afternoon with no testing, and be yelling Bifurcation occsaionally, as best I can tell bifurcation has nothing to do with anything). All that being said, it more or less worked for us (meaning in the evenings beer was tracked appropriately).
IGNORED_WORDS = set(open(os.path.join(settings.ROOT_PATH, 'djangocon', 'ignores.txt')).read().split())
def trending_topics(request):
logs = sorted(os.listdir(LOG_DIRECTORY), reverse=True)[:4]
tweets = []
for log in logs:
f = open(os.path.join(LOG_DIRECTORY, log), 'r')
for line in f:
tweets.append(simplejson.loads(line)['text'])
words = defaultdict(int)
for text in tweets:
prev = None
for word in text.split():
word = word.strip(string.punctuation).lower()
if word.lower() not in IGNORED_WORDS and word:
words[word] += 1
if prev is not None:
words['%s %s' % (prev, word)] += 1
words[prev] -= 1
words[word] -= 1
prev = word
else:
prev = None
trending = sorted(words.items(), key=lambda o: o[1], reverse=True)[:15]
if request.user.is_staff:
trending = ['%s - %s' % (word, count) for word, count in trending]
else:
trending = [word for word, count in trending]
return HttpResponse(simplejson.dumps(trending))
|
I have created a cron job for my website which runs every 2hours and it counts the words in the feeds and then displays the 10 highest count words as the hot topics.
Something that Twitter does on their homepage, is to show the most popular topics that are being discussed.
What my cron job does right now is it counts the words except for the words that i have mentioned, words like:
array('of', 'a', 'an', 'also', 'besides', 'equally', 'further', 'furthermore', 'in', 'addition', 'moreover', 'too',
'after', 'before', 'when', 'while', 'as', 'by', 'the', 'that', 'since', 'until', 'soon', 'once', 'so', 'whenever', 'every', 'first', 'last',
'because', 'even', 'though', 'although', 'whereas', 'while', 'if', 'unless', 'only', 'whether', 'or', 'not', 'even',
'also', 'besides', 'equally', 'further', 'furthermore', 'addition', 'moreover', 'next', 'too',
'likewise', 'moreover', 'however', 'contrary', 'other', 'hand', 'contrast', 'nevertheless', 'brief', 'summary', 'short',
'for', 'example', 'for instance', 'fact', 'finally', 'in brief', 'in conclusion', 'in other words', 'in short', 'in summary', 'therefore',
'accordingly', 'as a result', 'consequently', 'for this reason', 'afterward', 'in the meantime', 'later', 'meanwhile', 'second', 'earlier', 'finally', 'soon', 'still', 'then', 'third'); //words that are negligible
But this does not completely solve the issue of eliminating all the non-required words. And give only the words that are useful.
Can someone please guide me on this, and tell me how can I improve my algorithm.
|
How to improve my Algorithm to find the Hot-Topics like twitter does
|
Any particular reason you don't want to use a normal crontab?
% echo "* * * * * /Users/paul/Desktop/1.sh" | crontab -
This command should add a cron job that runs once per minute.
NOTE that this command will also replace any crontab that you already have. The crontab - command should be used with caution, as a short-cut.
If you want to edit an existing crontab, so as to avoid obliterating previously set jobs, you can use crontab -e. (If it launches vim and you don't know how to use vim, you can exit by hitting ESC:q!Enter and then go find editor documentation.)
If you want instructions on how to edit crontabs, type man crontab at your shell. If you want syntax information on the crontab file, man 5 crontab will show you that.
Enjoy!
UPDATE: (per comments)
To run your job every 30 seconds requires a simple hack. Cron only runs jobs on a per minute basis, so to run things every 30 seconds, you can have two jobs, one of which has a 30 second delay. For example:
#Mn Hr Da Mo DW Command
* * * * * /Users/paul/Desktop/1.sh
* * * * * sleep 30; /Users/paul/Desktop/1.sh
Hope this helps.
|
I want to start up a file with .sh type or .py on mac os x without using root ,
I searched in google and found launchctl can help me ,
so i read tutorial and do same in tutorial but it not work for me , [i using mac os x 10.9 x64]
My .plist file [run 1.sh file in every 60second] :
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.alvin.crontabtest</string>
<key>ProgramArguments</key>
<array>
<string>/Users/paul/Desktop/1.sh</string>
</array>
<key>Nice</key>
<integer>1</integer>
<key>StartInterval</key>
<integer>60</integer>
<key>RunAtLoad</key>
<true/>
<key>StandardErrorPath</key>
<string>/tmp/AlTest1.err</string>
<key>StandardOutPath</key>
<string>/tmp/AlTest1.out</string>
</dict>
</plist>
source of 1.sh:
echo '+' >> /Users/paul/Desktop/worked.txt
I put Run.plist in /Users/paul/Run.plist
and run command from terminal :
launchctl load /Users/paul/Run.plist
Launchctl start com.alvin.crontabtest
commands execute without any error but i not see
anything in worked.txt
can anyone help me please ?
|
Run a shell script periodically on Mac OS X without root permission
|
set the following property to Forbid in CronJob yaml
.spec.concurrencyPolicy
https://kubernetes.io/docs/concepts/workloads/controllers/cron-jobs/#concurrency-policy
|
I have scheduled the K8s cron to run every 30 mins.
If the current job is still running and the next cron schedule has reached it shouldn't create a new job but rather wait for the next schedule.
And repeat the same process if the previous job is still in Running state.
|
Kubernetes CronJob - Skip job if previous is still running AND wait for the next schedule time
|
31
Running a program that demands a terminal via cron can lead to problems; it won't have a terminal when it is run by cron.
In case of doubt, though, ensure that the variable is set in the script, by adding a line:
export TERM=${TERM:-dumb}
If the environment variable TERM is already set, this is a no-op. If it is not, it sets the terminal to a standard one with minimal capabilities — this satisfies the program that complains about TERM not being set.
Share
Improve this answer
Follow
answered Oct 17, 2013 at 12:39
Jonathan LefflerJonathan Leffler
741k142142 gold badges925925 silver badges1.3k1.3k bronze badges
0
Add a comment
|
|
I am having a script runonce.sh who calls another script setup.sh through cron. We consider this case as ideal case where "TERM environment variable not set." is seen in output of runonce.sh script.
Now I am facing a problem that another third simple script - upgradeAndTest.sh when calls setup.sh, that time also "TERM environment variable not set." is seen in output of upgradeAndTest.sh script. Why is so..?
Also, if I redirect stderr of setup.sh to stdout in calling script then also "TERM environment variable not set." displays on console.
Can any one help me to remove this line from stdout of calling script..?
|
how to remove "TERM environment variable not set"
|
If you are going to create subscription-level task, than you can create cron/windows scheduler task in:
"Subscriptions" > your subscription > "Websites & domains" > click on "Show advanced operations" > "Scheduled Tasks" > there will be only one name of FTP user of your subscription.
Note: Pay attention to interface changes for Plesk 11.5 and Plesk 12+ - there is no need to open "Show advanced operations".
The latest Plesk 12.5 provide a lot of options to cover most of the task cases:
Plesk 12.5
Other Plesk versions support only "Run a command" option:
Plesk 12.0
Plesk 11.5
If you need just answer, in "Server" -> "Scheduled Tasks" you can choose:
FTP user of your subscription mysite.com
your can choose root, but it's not recommended for security reasons.
For Plesk version below 12.5 to schedule execution of PHP script on Windows there is two ways:
Direct call of php binary with your script as argument.
Path to executable file: C:\Program Files (x86)\Parallels\Parallels Panel\Additional\PleskPHP55\php.exe
Arguments: path to you script like C:\inetpub\vhosts\domain.tld\httpdocs\script.php
Note: Pay attention to interpretation path, ...Additional\PleskPHP55\php.exe it path for PHP 5.5, you can change PleskPHP55 to PleskPHP5, PleskPHP53 or PleskPHP54 to use another PHP version.
Call script via request to your site:
Path to executable file: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
Arguments: -c "(new-object system.net.webclient).downloadstring('http://domain.test/script.aspx')"
|
I'm trying to setup a cron task in Plesk to run a short script every 5 minutes, I've just moved from a managed hosting account to a full access Plesk VPS, and I'm a little lost on a couple of things, this one in particular, when I go to Server > Scheduled Tasks I get a list of 'system users' as below, but I'm not sure under which user to make the cron task, any ideas?
adm
apache
bin
daemon
ftp
games
gopher
.. going all the way down to webalizer
The cron script path is below if that's relevant as to which user to choose -
/var/www/vhosts/mysite.com/httpdocs/scripts/index.php
|
Setting up cron task in Plesk 11
|
To create a cron job as root, edit your cron file:
[sudo] crontab -e
Add a new line at the end, every line is a cron job:
25 10 * * * php /var/www/<siteName>/artisan <command:name> <parameters>
This will execute the same command at 10:25AM everyday.
Just make sure you keep a blank line after the last one. And you also might need to use the full path of your php client:
25 10 * * * /usr/local/bin/php /var/www/<siteName>/artisan <command:name> <parameters>
|
This question already has answers here:
Cron Job with Laravel 4
(4 answers)
Closed 8 years ago.
I am trying to develop a cron job for a command I have already created. I am completely new to cron jobs so I dont really know how it works.
Trying the command by myself in the console works perfectly. All I need is to be able to execute it every 24 hours. I am using Laravel 4, can anyone help?
Thanks!
|
Cron Job in Laravel [duplicate]
|
DB Connections have a timeout which will cause this error if you try to send a query sometime after opening the connection. The usual scenario is:
Open DB connection
Fetch some data from DB
Do stuff, e.g. send emails (takes time longer than DB connection timeout)
Query DB using same connection
Error: MySQL server has gone away
So - what's the solution? You could simply increase the timeout, but that's ugly and could cause problems when traffic to your site increases. The best solution would be to close your DB connection and then re-open it like this:
Open DB connection
Fetch some data from DB
Close DB connection
Do stuff, e.g. send emails (takes time longer than DB connection timeout)
Open new DB connection
Query DB using same connection
Close DB connection
Here's more information:
http://dev.mysql.com/doc/refman/5.0/en/gone-away.html
|
I am working on Magento site and I get this error:
SQLSTATE[HY000]: General error: 2006 MySQL server has gone away on running
cron job magento
I only get this error sometimes.
<?php
class Namespace_Module_Model_Observer
{
public function importemails(Varien_Event_Observer $observer)
{
echo "Hi Dear";exit();
/* connect to gmail */
$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = '[email protected]';
$password = 'mypass';
/* try to connect */
$inbox = imap_open($hostname,$username,$password)
or die('Cannot connect to Gmail: ' . imap_last_error());
/* grab emails */
$emails = imap_search($inbox,'ALL');
/* if emails are returned, cycle through each... */
if($emails) {
/* begin output var */
$output = '';
/* put the newest emails on top */
rsort($emails);
/* for every email... */
foreach($emails as $email_number) {
/* get information specific to this email */
$overview = imap_fetch_overview($inbox,$email_number,0);
$message = imap_fetchbody($inbox,$email_number,2);
/* output the email header information */
$output.=
'<div class="toggler '.($overview[0]->seen ? 'read' : 'unread').'">';
$output.= '<span class="subject">'.$overview[0]->subject.'</span> ';
$output.= '<span class="from">'.$overview[0]->from.'</span>';
$output.= '<span class="date">on '.$overview[0]->date.'</span>';
$output.= '</div>';
/* output the email body */
$output.= '<div class="body">'.$message.'</div>';
}
echo $output;
}
/* close the connection */
imap_close($inbox);
}
}
This code works for several hours then it gives this error. What does the error mean?
|
SQLSTATE[HY000]: General error: 2006 MySQL server has gone away on running cron job magento
|
@Scheduled(cron="0 9 25 1 * ?")
This is on January 1st only, and the time is invalid, you'll want this instead:
@Scheduled(cron="0 0 9 25 * ?")
Reference: CronSequenceGenerator
|
How to write cron expression to trigger a function on 25th of every month at 9 A.M in the morning?
When I execute this code,
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
@Service
public class PayrollSchedulerImpl implements PayrollScheduler{
@Scheduled(cron="0 9 25 1 * ?")
public void calculateSalaryScheduled()
{
calculateSalary();
}
public void calculateSalary()
{
/* */
}
}
I get the error,
java.lang.StackOverflowError
sun.util.calendar.ZoneInfo.getOffsets(Unknown Source)
sun.util.calendar.ZoneInfo.getOffsets(Unknown Source)
java.util.GregorianCalendar.computeFields(Unknown Source)
java.util.GregorianCalendar.computeTime(Unknown Source)
java.util.Calendar.updateTime(Unknown Source)
java.util.Calendar.complete(Unknown Source)
java.util.Calendar.get(Unknown Source)
org.springframework.scheduling.support.CronSequenceGenerator.doNext(CronSequenceGenerator.java:130)
|
Cron expression to trigger on 25 of every month
|
14
Very first example they have in the documentation is...
Example: Run the tasks.add task every 30 seconds.
from datetime import timedelta
CELERYBEAT_SCHEDULE = {
"runs-every-30-seconds": {
"task": "tasks.add",
"schedule": timedelta(seconds=30),
"args": (16, 16)
},
}
Share
Improve this answer
Follow
answered May 15, 2012 at 8:41
vartecvartec
133k3636 gold badges221221 silver badges246246 bronze badges
2
4
I need it to run every 30 seconds DURING SPECIFIC HOURS. I too came across the very first example they have in the documentation.
– snakesNbronies
May 16, 2012 at 19:15
am also looking for a solution to this (and came across this post). would be really nice if timedelta could be combined w/crontab.
– brizz
Apr 29, 2015 at 1:34
Add a comment
|
|
Is it possible to run the django celery crontab very 30 seconds DURING SPECIFIC HOURS?
There are only settings for minutes, hours and days.
I have the crontab working, but I'd like to run it every 30 seconds, as opposed to every minute.
Alternatively...
Is it possible to turn the interval on for 30 seconds, and turn on the interval schedule only for a certain period of the day?
|
Django celery crontab every 30 seconds - is it even possible?
|
You could try to use ulimit -t [number of seconds] in the cronjob before running the script.
|
I have written a script that gets data from solr for which date is within the specified period, and I run the script using as a daily cron.
The problem is the cronjob does not complete the task. If I manually run the script (for the same time period), it works well. If I reduce the specified time period, the script runs from the cron as well. So my guess is cronjob is timing out while running the script is there is much data to process.
How do I increase the timeout for cronjob?
PS - 1. The script I am running in cronjob is a bash script which runs a python script.
|
How do I increase timeout for a cronjob/crontab?
|
16
This message is normal because you still do not have any crontab for that user:
no crontab for foo - using an empty one
Regarding the following:
nano / vim: No such file or directory
crontab: "nano" exited with status 1
It is happening because you are not defining the editor properly. To do so, you have to specify the full path of the binary:
export EDITOR=/usr/bin/nano
or
export EDITOR=/usr/bin/vi
Share
Improve this answer
Follow
answered Feb 18, 2014 at 9:18
fedorquifedorqui
281k105105 gold badges565565 silver badges607607 bronze badges
12
Yeah but I also tried to set my editor with the 2 lines you gave above. Still doesn't work.
– Hito
Feb 18, 2014 at 9:20
Well first check what is the path of your nano with which nano. My /usr/bin/nano is just an example.
– fedorqui
Feb 18, 2014 at 9:22
I also did it and it gave me /usr/bin/nano too.
– Hito
Feb 18, 2014 at 9:32
And you are still getting the "no such file or directory"?
– fedorqui
Feb 18, 2014 at 9:33
Yes. To summarize, I did : EDITOR=/usr/bin/nano export EDITOR crontab -e and I'm still getting : /usr/bin/nano: No such file or directory
– Hito
Feb 18, 2014 at 9:36
|
Show 7 more comments
|
I'm trying to edit my crontab, but I just can't open it!
So with my user foo, I just type:
crontab -e
Then I got:
no crontab for foo - using an empty one
nano: No such file or directory
crontab: "nano" exited with status 1
So I tried first:
export EDITOR=nano
I retried and I got exactly the same output. I also tried to set my editor to Vim with:
export EDITOR=vim
no crontab for foo - using an empty one
vim: No such file or directory
crontab: "vim" exited with status 1
But I keep getting the same output again and again. How can I open my crontab and then edit it?
|
Can't edit crontab
|
Someone on the Celery's IRC channel give me the right way to do that by using the "worker_ready.connect" signal: http://docs.celeryproject.org/en/latest/userguide/signals.html#worker-ready
from celery.signals import worker_ready
@worker_ready.connect
def at_start(sender, **k):
with sender.app.connection() as conn:
sender.app.send_task('app.modules.task', args,connection=conn, ...)
It works like a charm now!
|
I have a task which needs to be launched when Celery starts. This tasks is next runned every 5 minutes through a callback / eta.
I find some threads about it but nothing which seems to work on Celery 3.
Thanks for your help,
Arnaud.
|
Celery: launch task on start
|
In addition to what Paul C said you could create a decorator that checks the X-Appengine-Cron header as illustrated below. Btw, the header can't be spoofed, meaning that if a request that hasn't originated from a cron job has this header, App Engine will change the header's name. You could also write a similar method for tasks, checking X-AppEngine-TaskName in this case.
"""
Decorator to indicate that this is a cron method and applies request.headers check
"""
def cron_method(handler):
def check_if_cron(self, *args, **kwargs):
if self.request.headers.get('X-AppEngine-Cron') is None:
self.error(403)
else:
return handler(self, *args, **kwargs)
return check_if_cron
And use it as:
class ClassName(webapp2.RequestHandler):
@cron_method
def get(self):
....
|
GAE provides cron jobs for scheduled jobs. How do I set some security to prevent someone from executing the http GET directly? In the following example, I can type /updateData anytime in the url field of a browser to execute the job in the following settings:
cron:
- description: daily update of the data in the datastore
url: /updateData
schedule: every day 00:00
timezone: ...
|
Google app engine: security of cron jobs
|
Jobs scheduled by node_cron won't run when your free dynos are sleeping.
As an alternative, you can use the Heroku Scheduler add-on to schedule your cron jobs. That will trigger one-off dynos to run your cron jobs. Provided you don't exceed your monthly allowance of free dyno hours, you will be able to run your cron jobs for free.
|
So I know Heroku's free dynos 'wind down' when there isn't any traffic to them– how would this effect the cron jobs that I've implemented using the node-cron module?
|
Heroku and node-cron?
|
20
Yes the cron time is correct.
1 0 * * * /mydir/myscript
should be your cron entry.
Each cron entry consists of six fields, in the following order:
minute(s) hour(s) day(s) month(s) weekday(s) command(s)
0-59 0-23 1-31 1-12 0-6
Share
Improve this answer
Follow
edited Jul 7, 2017 at 22:31
answered Oct 5, 2015 at 13:34
Natarajan ChidhambharamNatarajan Chidhambharam
20111 silver badge55 bronze badges
1
@Abhinavbhardwaj I have tried this & it works. Thanks Natarajan
– Nishant
Jan 8, 2021 at 18:26
Add a comment
|
|
I want to execute cron every day on midnight at time 00:01 Hrs.
Is the following cron time correct?
1 0 * * * *
|
How to executing cron one minute after midnight every day?
|
Use the --defaults-extra-file option to tell it where to find the .my.cnf file (assuming it's readable by whichever user is running mysqldump.
|
I have tried to make backup cron job on my webserver running FreeBSD. Currently it looks something like this:
/usr/local/bin/mysqldump --opt --single-transaction --comments --dump-date --no-autocommit --all-databases --result-file=/var/backups/mysql/all.sql
It works fine when I run it as root (since root has a .my.cnf with the username and password used to connect, but when the job is run by cron, the my.cnf file is not read.
Is there any way around that without having to put username and password into the command itself (since that's kinda insecure)?
Strangely, I have the same setup with PostgreSQL and a .pgpass file, and that works like a charm.
|
Secure MySQL backup cron job – my.cnf is not being read
|
16
Try altering your php.ini file in both php/[version]/apache2 to resemble this:
extension=mysqlnd
extension=mysqli
Loading mysqlnd first eliminates the error on my debian VM. If you intend to run the same code at the command line, you may wish to consider altering php/[version]/cli/php.ini as well.
Share
Improve this answer
Follow
answered Nov 28, 2020 at 6:07
Michael McPhersonMichael McPherson
48866 silver badges1717 bronze badges
2
1
this worked for me on CentOS 7 running MySQL 8 and PHP 7.4... nothing else worked but this did... thank you!
– aequalsb
Mar 2, 2022 at 23:59
1
Works on legacy Ubuntu, PHP 7.2
– Duco
Apr 4, 2022 at 21:38
Add a comment
|
|
My entire site runs flawlessly via browser. I have just added a cron job, and each time it runs this error gets triggered:
PHP Startup: Unable to load dynamic library 'mysqli' (tried: /usr/lib/php/20180731/mysqli (/usr/lib/php/20180731/mysqli: cannot open shared object file: No such file or directory), /usr/lib/php/20180731/mysqli.so (/usr/lib/php/20180731/mysqli.so: undefined symbol: mysqlnd_global_stats))
Not sure what is going on. I have logged PHP version both using the browser, and using cron, and it came out the same: 7.3.2-3+0~20190208150725.31+stretch~1.gbp0912bd
What is so different in cron? How can i fix this?
|
PHP Startup: Unable to load dynamic library 'mysqli' undefined symbol: mysqlnd_global_stats
|
import sqlite3
import os
dir_path = os.path.dirname(os.path.abspath(__file__))
db = sqlite3.connect(os.path.join(dir_path, 'my_db.db'))
cur = db.cursor()
...
Remember that Python's os.path module is your best friend when manipulating paths.
|
I'm setting up my first cron job and it's not working. I think the problem may be a relative path issue.
Given cron job:
*/1 * * * * python2.7 /home/path/to/my/script/my_script.py
and my_script.py:
import sqlite3
db = sqlite3.connect('my_db.db')
cur = db.cursor()
...
How do I make sure that my_script.py looks for my_db.db in /home/path/to/my/script/ (the same directory that houses my_script.py) and not whatever directory crontab lives?
Other suggestions for troubleshooting are also welcome.
Note - I think the issue may be a path issue because when I try running my_script.py using python2.7 /home/path/to/my/script/my_script.py from any location other than /home/path/to/my/script/, I get an "unable to open database" error.
|
Relative paths in scripts executed by cron jobs
|
11
self.scheduler = BlockingScheduler(
logger=log,
job_defaults={'misfire_grace_time': 15*60},
)
adding the misfire_grace_time as job_defaults will work
Share
Improve this answer
Follow
edited Jun 15, 2019 at 0:02
AS Mackay
2,85199 gold badges1919 silver badges2626 bronze badges
answered Jun 14, 2019 at 23:31
deepak mahapatradeepak mahapatra
19533 silver badges99 bronze badges
Add a comment
|
|
I am running a BlockingScheduler process that it's suppose to run several cron jobs, but it fails to run every single time with the message:
Run time of job "validation (trigger: cron[hour='3'], next run at: 2016-12-30 03:00:00 CST)" was missed by 0:00:02.549821
I have the following setup:
sched = BlockingScheduler(misfire_grace_time=3600, coalesce=True)
sched.add_jobstore('mongodb', collection='my_jobs')
@sched.scheduled_job('cron', hour=3, id='validation')
def validation():
rep = Myclass()
rep.run()
if __name__ == '__main__':
sched.start()
I thought adding misfire_grace_time would do the trick, but every job is still missing to run.
|
APScheduler missing jobs after adding misfire_grace_time
|
18
All cron jobs (in a Debian based system like Ubuntu) are logged in /var/log/syslog. You are looking for "CRON" in all caps, so first step is to do a case insensitive search:
grep -i cron /var/log/syslog
Next, syslog may only show the last 24 hours or less meaning you may not see the daily entry in there. Try searching old syslog files as well:
zgrep -i cron /var/log/syslog*
You should be able to narrow down the results even further using:
zgrep -i cron.daily /var/log/syslog*
Share
Improve this answer
Follow
edited Jun 11, 2015 at 15:40
answered Jun 11, 2015 at 5:15
Martin KonecnyMartin Konecny
58.7k2020 gold badges141141 silver badges159159 bronze badges
4
Great.. thanks! This worked. The last command only gave me last 6 days. Does it display 6 days/week at a time?
– am3
Jun 11, 2015 at 5:19
Unfortunately all syslog files after 6 days are discarded. Take a look into /etc/logrotate.d/rsyslog to change this behaviour.
– Martin Konecny
Jun 11, 2015 at 5:29
Thanks. Now I can just change the rotate value to have more logs.
– am3
Jun 11, 2015 at 5:38
You can also change how often it rotates (weekly instead of daily) so that you have 7 weeks instead of 7 days.
– Martin Konecny
Jun 11, 2015 at 5:39
Add a comment
|
|
I have a couple of cron jobs in cron.daily which are supposed to execute daily. I know these tasks get executed as I can see the end result. For example: I'm doing a back-up of MySQL DB and I can see the back-up file. However, I cannot find the log for this.
I checked /var/log/syslog with a grep CRON /var/log/syslog command all I can find is php5 session clean cronjob(I don't really know what that is)
Where can I find the log for cron.daily?
|
Log of cron.daily?
|
Try this out on your user's crontab:
@hourly DISPLAY=:0 xterm -e /path/to/my/script.sh
It will open (hourly) an xterm with your script executing, and exit after your script exits. Of course, you should modify the @hourly part to suit your needs.
|
In Linux, is there a way to run a cron job in the foreground (or interactive mode)? (I have a program that runs periodically to accept user input and do some processing. So I want to schedule it as a cron job that can run in the foreground).
|
Linux: Run cron job in foreground
|
Back in the day when there were no per-user crontabs, I often accomplished this using at(1).
#!/bin/sh
... do stuff...
at -f /path/to/me 5pm tomorrow
This way your script runs and schedules itself for the next invocation.
I don't think you can specify a timespec of "next weekend", so you'll just have to reschedule every day and have your script exit (after scheduling the next at job) if it is not a weekend.
Edit: Or instead of scheduling every day, find out what today is and schedule appropriately. e.g.
day=Saturday
if [ $(date +%u) -eq 6 ] ; then day=Sunday ; fi
at -f /path/to/me 5pm next $day
If this script is run on a Saturday, it schedules the next run for next Sunday, otherwise it runs next Saturday. [ $(date +%A) = Saturday ] may be more readable, buts %A will give a locale-specific string so may not work if you change locale.
|
I want to run a script once day (and only on weekends), however, I cannot use cron job for that.
I was thinking about having an infinite while loop, sleep for 24 hours, check if it is a weekend, and if so execute the script.
What it's a good solution under bash on linux?
my current implementation:
#! /bin/bash
while [ true ]; do
if [[ $(date +%u) -lt 6 ]]; then
./program
else
echo Today is a weekend, processing is skipped. Back to sleep.
fi
sleep 86400
done
And I will launch this script at 5 pm.
|
How to simulate a cron job
|
17
The correct syntax for every hour job is 0 * * * *.
But you can use both 0 0 * * * * and 0 0 */1 * * *
Since */1 means every 1 hour/minute/second like the *.
Share
Improve this answer
Follow
edited Nov 26, 2021 at 8:10
answered Nov 25, 2021 at 7:51
devblack.exedevblack.exe
50455 silver badges1818 bronze badges
1
1
they both are doing the same work for me, running at every hour
– N.A
Nov 25, 2021 at 7:55
Add a comment
|
|
This question already has an answer here:
Is `*/1 * * * *` and `* * * * *` equivalent in CRON?
(1 answer)
Closed 2 years ago.
This post was edited and submitted for review 2 years ago and failed to reopen the post:
Original close reason(s) were not resolved
Which one is the correct syntax for running a job at every hour?
0 0 * * * *
0 0 */1 * * *
Also how are they both different?
|
Running cron job/task at every hour [duplicate]
|
Azure function with timer trigger will only run one job at a time. If a job takes longer then next one is delayed.
Quoting from Wiki
If your function execution takes longer than the timer interval,
another execution won't be triggered until after the current
invocation completes. The next execution is scheduled after the
current execution completes.
That is true even if you scale out.
https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-timer#scale-out
You may want to ensure that your function does not time out on you. See https://buildazure.com/2017/08/17/azure-functions-extend-execution-timeout-past-5-minutes/ on how to configure function timeout.
|
I was wondering if anybody knows what happens if you have a Cron setting on an Azure Function to run every 5 minutes if its task takes more than 5 minutes to execute. Does it back up? Or should I implement a locking feature that would prevent something, say in a loop, from handling data already being processed by a prior call?
|
Azure Functions Timer Trigger thread safety
|
You can have multiple commands in a single crontab line. Just separate them with semicolons:
crontab -l | { /bin/cat; /bin/echo "* 3 * * * cd /etc/application ; scrapy crawl"; } | crontab -
|
I have a quick question. I need to add a cron to my debain crontab using an automated shell script and I need the cron to do two things:
cd into /etc/application
run the command "scrapy crawl"
crontab -l | { /bin/cat; /bin/echo "* 3 * * * cd /etc/application"; }
| crontab -
How do I get it to also run the scrapy crawl command?
|
Run two commands with a crontab
|
Things got much easier lately, please see this link https://azure.microsoft.com/en-us/services/scheduler/ to create a scheduled job in the new Azure Scheduler. There is a basic Free tier as well as some paid options but I think this is exactly what many of us were looking for. It is an excellent solution for triggering URLs with GET,POST,PUT,DELETE requests.
Just follow the simple instructions. Starting by selecting "Scheduler" from the Azure dashboard app menu:
|
Is there a way to use the windows scheduled task to kick off a url or a exe on a schedule?
Can I write a program as an exe then create a Azure VM then RDP into the Azure VM and hook it up to windows task scheduler?
|
How can I set up a CRON job using Windows Azure?
|
Just write a normal PHP script -- make one that will work if it's launched directly from the browser. Then schedule that very same PHP file to run in cron, using this as a guide:
http://www.unixgeeks.org/security/newbie/unix/cron-1.html
Basically, using the values at the beginning, specify the schedule (minute, hour, day of week, day of month, etc.). Then set the user it runs as, which is likely to be "apache" or whatever your web server daemon is running under. Then set the "command" that cron is running to be php php_email_script.php (where "php_email_script.php" is the name of your PHP file.
|
i managed to send multiple emails (check here).i am stuck with sending automated emails via cron.
This is what i need - while the admin send emails, i store the message, emails, event date in the database. now i am trying to set a cron job to send emails to all these ids from the table with the message i have as a reminder. i am not familiar with cron job scripting, can anyone help in guiding me the right way to write script that i can place in cron tab. I am planning to send two mails - one day exactly before the event and on the day of event.thanks
|
How to send emails via cron job usng PHP mysql
|
I find out that I can simply add the correct which node path to $PATH.
$which node
/usr/local/bin/node
$sudo su
$which node
/usr/bin/node
$export PATH=$PATH:/usr/local/bin
$node -v
v7.2.0
|
I am facing a problem as posted here, and notified that the cause may be the version of nodejs.
As shown below, the node version is fine.
$node -v
v7.2.0
But it gives me an abnormal version of the root user, which is used by crontab process.
$sudo su
$node -v
v0.10.42
I've tried $n rm 0.10.42 or $n 7.2.0 many times won't fix the problem
Can someone help? I want the crontab process to use the correct version of nodejs.
|
How to switch Nodejs Version of root user?
|
use your browser to hit http://yourdomain.com/cron.php or php-cli to execute cron.php in the root of the application.
|
I want to run the Magento cron by manually . I can remember in Drupal we can do it manually without setting the cron job in the server. Same like i want to do run the magento's cron in my local system. How i can do this??
|
Magento : how to run cron manually in local machine?
|
a crontab is defined like this:
MIN HOUR DOM MON DOW CMD
so if you want to run a task on a daily basis try:
0 0 * * * /path/to/your/script
that will trigger the launch of your script everyday at 0:00
For more details, see the cron tag wiki
|
Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 11 years ago.
Improve this question
I am using sphinx for searching. I get new data everyday which is added in the database.
I have to add this data into the sphinx search index so that it can be searched. For that I need to reindex the sphinx search index at regular intervals.
How can I set a cron in linux to do so?
|
How to add a cron job in linux [closed]
|
Using Crontab to make asynchronous tasks (asynchronous from your PHP code) is a basic approach where using a job/task queue manager is an elaborate one and give you more control, power and scalability/elasticity.
Crontab are very easy to deal with but does not offer a lot of functionalities. It is best for scheduled jobs rather than for asynchronous tasks.
On the other hand, deploying a Task queue (and its message broker) require more time. You have to choose the right tools first then learn how to implement them in your PHP code. But this is the way to go in 2011.
Thank God, I don't do PHP but have played around with Celery (coupled with RabbitMQ) on Python projects ; I am sure you can find something similar in the PHP world.
|
We have a large web application built on PHP. This application allows scheduling tweets and wall posts and there are scheduled emails that go out from the server.
By 'scheduled', I mean that these are PHP scripts scheduled to run at particular time using cron. There are about 7 PHP files that do the above jobs.
I have been hearing about Message Queues. Can anyone explain if Message Queues are the best fit in this scenario? Do Message Queues execute PHP scripts? or do we need to configure this entirely differently? What are the advantages / disadvantages?
|
Difference between using Message Queue vs Plain Cron Jobs with PHP
|
I came up with a working example since I found your question interesting and have been interested in this problem before. It's based entirely on the source code so I have no idea if it comes close to following best practice. Nonetheless, you may be able to tune it to your needs. FYI, you don't necessarily need to create a new ScheduledTaskRegistrar object - I figured that since your objective is a dynamic scheduler, you wouldn't be interested in defining your tasks purely in the overwritten method.
@SpringBootApplication
public class TaskScheduler implements SchedulingConfigurer, CommandLineRunner {
public static void main(String[] args){SpringApplication.run(TaskScheduler.class, args);}
List<CronTask> cronTasks;
@Override
public void run(String... args) throws Exception {
CronTask task = this.createCronTask(new Runnable() {
@Override
public void run() {
System.out.println(LocalDateTime.now());
}
}, "1/10 * * * * *");
ScheduledTaskRegistrar taskRegistrar = new ScheduledTaskRegistrar();
taskRegistrar.addCronTask(task);
configureTasks(taskRegistrar);
Thread.sleep(51);
taskRegistrar.destroy();
taskRegistrar = null;
ScheduledTaskRegistrar taskRegistrar2 = new ScheduledTaskRegistrar();
taskRegistrar2.addCronTask(task);
configureTasks(taskRegistrar2);
}
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
// "Calls scheduleTasks() at bean construction time" - docs
taskRegistrar.afterPropertiesSet();
}
public CronTask createCronTask(Runnable action, String expression) {
return new CronTask(action, new CronTrigger(expression));
}
}
I have experience using cron jobs in Azure and other places. Programming in Java, I have typically used @Scheduled with fixed times just for the sake of simplicity. Hope this is useful to you though.
|
In spring boot, can I schedule a spring job by not using @Scheduled annotation to a method?
I am working with spring job in the spring boot. I want to schedule a job by using cron expression, but without using @Scheduled(cron = " ") annotation to the method.
I know that I can schedule a job inside this method as below.
@Scheduled (cron = "0 10 10 10 * ?")
public void execute() {
/ * some job code * /
}
But I want it to be dynamic so that I can take a cron expression as input from the user and schedule it.
|
How to schedule a cron job in spring boot without using @Scheduled() annotation
|
Technically the schedule method ist called via the constructor of Illuminate\Foundation\Console\Kernel ( This is the parent class of app\Console\Kernel.php)
So every time the console Kernel is instantiated, the schedule() method gets executed.
Let's see what gets executed in which scenario ( $schedule->call() can be replaced with $schedule->command() or $schedule->exec()):
protected function schedule(Schedule $schedule)
{
// everything that is inside the schedule function is executed everytime the console kernel is booted.
// gets exectuted every time
\App\User::where('foo', 1)->get();
$schedule->call(function() {
// gets executed for every call to php artisan schedule:run
\App\User::where('foo', 1)->get();
});
$schedule->call(function() {
// gets executed for every call to php artisan schedule:run
// IF the closure in the when() function is true;
\App\User::where('foo', 1)->get();
})->when(function() {
// if true is returned the scheduled command or closure is executed otherwise it is skipped
\Schema::hasColumn('user', 'foo');
});
}
But why HAS the schedule command to be exectuted with every command?
Well, obviously php artisan schedule:run is a console command itself. So it definitely needs information about scheduled commands.
Also other commands could need information about scheduled commands... For example if you want to write an artisan command list:scheduledTasks. This command would require that all scheduled commands have been added to the console schedule list.
Maybe there are several other (internal) arguments why the schedule function has to run everytime. ( I did not dig too deep in the source code... )
Nevertheless... information about scheduled commands could be useful to a variety of use cases.
|
I have one table called dc_user_meta and I've created one artisan command and scheduled it in kernel.php. Just after cloning the repository, when I try to run PHP artisan migrate, I get this error.
[Illuminate\Database\QueryException]
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'database.dc_user_meta' doesn't exist (SQL: select * from `dc_user_met
a` where `meta_key` = usage_in_days)
Not only php artisan migrate but I am unable to run any artisan command at all! I don't know why PHP keeps calling schedule method every time I try to execute any artisan command.
Here in this case, What I can do to solve this error is put the cover over my logic in schedule method just like this.
if(Schema::hasTable('dc_user_meta')){
// Code here
}
But I don't think it's good in Long run. What's the right way to solve this error?
UPDATE:
I just tried covering call to command in kernel.php just like this but still no success!
if(Schema::hasTable('dc_user_meta')){
$schedule->command('usage:update')->daily();
}
UPDATE:
I got the solution. But I don't think it's the answer to the question. It solves my problem but I don't think it's standard Solution. I just covered by Command login just like this.
kernel.php0
Any specific answer to why Laravel calls schedule() with every kernel.php1 command and how to solve the error in a standard way if something like this happens!
|
Why Laravel keeps calling schedule() with every Artisan Command?
|
Ice Cube seems to specialize in setting up very complicated schedules (occurs on the 1st and 4th wednesdays, but only if they're even numbered days, and not if a weekend, etc.)
If that's what you need, then the task you described probably IS the most efficient way to run a number of tasks every day on that kind of complex schedule. If you don't need that complexity in your schedules, then you could look at something like whenever (as MatthewFord mentioned), which just uses cron schedules to setup tasks to be executed, but that's intended for admin-type tasks, and so requires a config file to be edited, and doesn't work if you need to be adding and removing things via your application interface.
Another option for using Ice Cube would be to have a monthly cron go through every schedule, and set up another table defining which events have to be run on which days for the next month. (each row has a date and a task definition), and your daily cron could select from that table...
You would also have to update that table for one month ahead of time every time one of the schedules changed in the application... kind of a hassle, so unless you have hundreds of thousands of schedules to look through once a day, it's probably not worth the trouble.
|
I want to create recurring events using the Ice Cube gem in Rails - my question is, how do I then correctly, or rather efficiently, use these recurring rules for triggering actual events?
An example of this would be a recurring invoice.
Say I have an Ice Cube recurrence set for once a week and I saved it to a recurring invoice row using to_yaml. I now have a row in the database with a serialized recurrence rule. The only way I can imagine using this is to run through each and every row in the database, unserializing the saved recurrence rules and checking whether it needs to run today with schedule.occurs_on?(Date.new) - this would then be put into a cronjob that runs daily:
items = RecurringItem.find(:all)
items.each do |item|
schedule = Schedule.from_yaml(item.schedule_yaml)
if schedule.occurs_on?(Date.new)
#if today is a recurrence, do stuff!
end
end
This looks terribly inefficient to me - but I might be doing it completely wrong. Is there no better way to use Ice Cube?
|
Correct way to use events created with Ice Cube in Rails using a daily cron job
|
2
I don't have a great cron specific answer for this but in case its helpful there are alternative schedulers which give you more information about the running jobs from a central view, something like Cisco's Tidal Scheduler
Share
Improve this answer
Follow
answered Feb 7, 2012 at 21:06
Mike K.Mike K.
3,7792929 silver badges4141 bronze badges
2
1
I found this tool : github.com/takumakanari/cronv, it seems to serve the exact purpose. Domo!
– computingfreak
Mar 7, 2019 at 7:47
Today i found a web-based crontab management tool, github.com/cronkeep/cronkeep worth sharing here i assume
– computingfreak
Oct 4, 2019 at 9:14
Add a comment
|
|
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 10 years ago.
Improve this question
I have crontabs for many machines, and wanted to see what started when, and to ensure load on the database server would be fine. Is there a tool that either converts crontab entries to iCal, or a tool that directly does visualization?
|
Is there a tool that allows visualization of crontab entries? [closed]
|
GK27's answer does not fully answer the question, so let me clarify:
cron will run jobs when the time matches the expression provided. Your expression tells it to run when the minute is divisible by 20 (*/20) and your hour range tells it to run when the hour is within the specified range inclusively (5-23). The remaining three * tell it to match any day, month, and any day of the week.
Therefore the first job will run at 05:00 because the hour, 05, is in the range 5 to 23 and the minute, 00, is divisible by 20. The last job will run at 23:40 because the hour, 23, is in the range 5 to 23 and the minute, 40, is divisible by 20. It will not run at 00:00 because the hour, 00, is not in the range 5 to 23.
|
Say I have a crontab which runs every 20 minutes and I have a hour range which can vary so lets say a-b, which in one example could look like
*/20 5-23 * * * /usr/bin/cool_program
My question is, will the cron run at 23:00, 23:20, 23:40 and 00:00 too?
|
Will crontab hour range a-b run after b too?
|
The Croniter package seems like it may get what you need. Example from the docs:
>>> from croniter import croniter
>>> from datetime import datetime
>>> base = datetime(2010, 1, 25, 4, 46)
>>> iter = croniter('*/5 * * * *', base) # every 5 minites
>>> print iter.get_next(datetime) # 2010-01-25 04:50:00
>>> print iter.get_next(datetime) # 2010-01-25 04:55:00
>>> print iter.get_next(datetime) # 2010-01-25 05:00:00
>>>
>>> iter = croniter('2 4 * * mon,fri', base) # 04:02 on every Monday and Friday
>>> print iter.get_next(datetime) # 2010-01-26 04:02:00
>>> print iter.get_next(datetime) # 2010-01-30 04:02:00
>>> print iter.get_next(datetime) # 2010-02-02 04:02:00
Per the code, it also appears to do validation on the entered format. Likely that you came across this already, but just in case :)
|
I am currently running a django web app in python where I store cron entries entered by the user into a database. I was wondering if there are any python libraries/packages that will validate these entries before I store them into the database. By validate I mean correct syntax as well as the correct range (ex: month cannot be 15). Does anyone have any suggestions? Thanks!
|
Cron parser and validation in python
|
A nice trick to get all environment properly set up in crontab is to use /bin/bash -l :
0 16 * * * /bin/bash -l -c '/mnt/voylla-production/releases/20131031003111/voylla_scripts/cj_4pm.sh'
The -l option will invoke a full login shell, thus reading your bashrc file and any path / rvm setting it performs.
If you want to simplify your crontab management and use this trick - as well as others - without having to think about them, you can use the Whenever gem. It also play very nice with capistrano, if you use it, regenerating crontab on deploy.
|
I'm trying to execute the following shell script using crontab:
#!/bin/sh
cd /mnt/voylla-production/current
bundle exec rake maintenance:last_2_days_orders
bundle exec rake maintenance:send_last_2_days_payment_dropouts
The crontab entry is
0 16 * * * /mnt/voylla-production/releases/20131031003111/voylla_scripts/cj_4pm.sh
I'm getting the following error message in the mail:
/mnt/voylla-staging/current/voylla_scripts/cj_4pm.sh: line 3: bundle: command not found
/mnt/voylla-staging/current/voylla_scripts/cj_4pm.sh: line 4: bundle: command not found
I dont get the error when I run the commands manually. Not sure what's going on here. Could someone please point out.
Thanks
|
bundle exec not working with crontab
|
As one other person has suggested, vim is obviously the default editor on your new server. You can test this by running
EDITOR=pico crontab -e
Substituting whatever is your actual preferred editor (sounds like it may be nano or pico). If that works, you should try one of the following:
edit your login script to set that environment variable on login (sets the editor just for that user)
Make sure your favourite editor is is installed and run the following (as root): update-alternatives --config sensible-editor
You can then choose the default editor for all users (they can override it individually by doing option 1).
|
I have had several Debian servers and always edited cronjobs in this way:
crontab -e
and
Ctrl+x
Just got a new server and can not do it in this way anymore.
When I enter crontab -e, the file opens but I can't write anything. I can move cursor up and down but can't write. I even can not exit from this file because Ctr+x doesn't work.
When I open a file there is some information and the rest empty lines contain tildes ~ in the beginning of each line.
Any ideas how can I edit this file?
Thanks.
|
Can not edit cronjobs file in Debian with crontab -e
|
Do you have a typo? It looks like you might have mis-typed Desktop?
Another thing to do is to redirect the output of running the script to a file so you can see what's going on like this:
1 * * * * /Users/apple/Destop/wget/down.sh >> /tmp/cron.out
and then check out the file to see what's going on.
|
I'm new to cron jobs. I read a post on how to write a cron job with crontab.
So my crontab looks like this:
1 * * * * /Users/apple/Desktop/wget/down.sh
which basically means that every minute i want to execute the script :down.sh. Now the script runs
fine manually. The script is a simple program that downloads a PDF from the internet:
#!/bin/bash
wget -U Mozilla -t 1 -nd -A pdf "http://www.fi.usj.edu.lb/images/stories/HoraireS08/3eli.pdf" -e robots=off;
I don't know why it's not running every minute once the terminal tells me that he's installing the new crontab.
Can somebody help me please?
Solution:
Thank you all for your help, the syntax as mcalex said should be
* */1 * * * path/to/script
if you want it to be executed every hour.
The cron job was working normally.However my mistake was simply writing permissions, in fact while executing the wget command, it's supposed to write the pdf file in the current workind directory which is a system directory in case of the cron tab. so i solved my problem simply by navigating to the Desktop directory before executing the wget command like so:
cd /Users/apple/Desktop/wget
and then do whatever i want to do.
PS: i should include the full path of the wget command too.
Thank you all for you help again:)
|
crontab is not running my script
|
There should not be a space between "*" and "/10". It should be:
*/10 * * * * /usr/bin/php /home/user/public_html/domain.com/private/update.php
|
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
I'm trying to run a cron job so that a php script will run every 10 minutes on my server. The script updates a database. Right now my crontab looks like:
* /10 * * * * /usr/bin/php /home/user/public_html/domain.com/private/update.php
However, the php script never seems to run. I've also tried reloading cron after updating the cron tab with :
$ /etc/init.d/cron reload
but this didn't work either. Does my current crontab look correctly formatted? Are there specific permissions that need to be specified on a file in order for it to run a script?
|
php cron job every 10 minutes [closed]
|
for any one still looking for a solution, in laravel 5.7 they added support to run all jobs in the queue and then stop the queue worker when all jobs are done.
Your cronjob should run this: php /path/to/laravel/artisan queue:work --stop-when-empty
Queue worker command source code on Github
plus there is a package available for older versions of laravel
orobogenius/sansdaemon
|
I am trying to get my website to send confirmations emails every time someone new register.
i did it like following after reading about it, but i am still not convinced that this is the best way to do it.
in my cron runs every minute and calls php artisan schedule:run
in my console/Kernel
protected function schedule(Schedule $schedule)
{
$schedule->command('queue:work --once')->everyMinute()->withoutOverlapping();
}
i added the --once parameter because the queue worker is not existing when finished, and i do not want to have many new processes running every minute.
is there a way to make the queue worker finish all the jobs and exit and then start it after one minute again so that i do not have many instances , or is it just one instance ??
i read that i can return null to exit the worker, but if this can be done, then how can i return null only after the last job is done?
|
Laravel queue worker with cron
|
A simple, non-Celery way to approach things would be to create custom django-admin commands to perform your asynchronous or scheduled tasks.
Then, on Windows, you use the at command to schedule these tasks. On Linux, you use cron.
I'd also strongly recommend ditching Windows if you can for a development environment. Your life will be so much better on Linux or even Mac OSX. Re-purpose a spare or old machine with Ubuntu for example, or run Ubuntu in a VM on your Windows box.
|
Something I've had interest in is regularly running a certain set of actions at regular time intervals. Obviously, this is a task for cron, right?
Unfortunately, the Internet seems to be in a bit of disagreement there.
Let me elaborate a little about my setup. First, my development environment is in Windows, while my production environment is hosted on Webfaction (Linux). There is no real cron on Windows, right? Also, I use Django! And what's suggested for Django?
Celery of course! Unfortunately, setting up Celery has been more or less a literal nightmare for me - please see Error message 'No handlers could be found for logger “multiprocessing”' using Celery. And this is only ONE of the problems I've had with Celery. Others include a socket error which it I'm the only one ever to have gotten the problem.
Don't get me wrong, Celery seems REALLY cool. Unfortunately, there seems to be a lack of support, and some odd limitations built into its preferred backend, RabbitMQ. Unfortunately, no matter how cool a program is, if it doesn't work, well, it doesn't work!
That's where I hope all of you can come in. I'd like to know about cron or a cron-equivalent, which can be set up similarly (preferably identically) in both a Windows and a Linux environment.
(I've been struggling with Celery for about two weeks now and unfortunately I think it's time to toss in the towel and give up on it, at least for now.)
|
Scheduling a regular event: Cron/Cron alternatives (including Celery)
|
It may be that you're using a different Python executable. On the shell, enter which python to find out where the Python executable is located. Let's say this returns something other than /usr/bin/python, say /home/myuser/bin/python, then in the first line of your script, you would write:
#!/home/myuser/bin/python
It may also be that your shell has environment variable called PYTHONPATH. If that's the case and you find where it's importing the library from, then this is how you would add the path to find the library in the first line of your script, before the import of "MySQLdb":
import sys; sys.path.append('/path/to/MySQLdb-lib/')
|
I am using crontab to run a python script that requires the module MySQLdb. When I run this script from the command line everything works fine. However, trying to run it using crontab elicits this error.
Traceback (most recent call last):
File "clickout.py", line 3, in <module>
import MySQLdb
ImportError: No module named MySQLdb
I did a google search and added this to the top of my script #!/usr/bin/python. However, this didn't do anything and I am still getting the same error. What am I doing wrong?
|
Cannot Import Python MySQL module when running a script using crontab
|
There is seemingly right now an error with those browsecap files. They seem to contain unescaped semicolons ";" in the browser spec. You can fix that using this little script:
<?php
$browsecap = file('browscap.ini');
foreach( $browsecap as &$row )
if ( $row[ 0 ] == '[' )
$row = str_replace( ';', '\\;', $row );
file_put_contents( 'fixed_browscap.ini', $browsecap );
|
I have a cronjob that summarize browser statistics. This cronjob loads data and then use the get_browser() PHP function to parse the browser information.
Here's what I did:
cd /etc/php5/cli/conf.d
me@ubutnu:/etc/php5/cli/conf.d$ sudo wget http://browsers.garykeith.com/stream.asp?Lite_PHP_BrowsCapINI -O browscap.ini
2011-09-30 15:14:18 (890 KB/s) - `browscap.ini' saved [185384/185384]
Then the cronjob run:
php /usr/local/cron/summarizeStats.php --option=browserStats --date=yesterday
and I get this error:
PHP: syntax error, unexpected $end, expecting ']' in /etc/php5/cli/conf.d/browscap.ini on line 51
What am I doing wrong? Thanks
|
Browscap.ini throwing an error when loading PHP (command line - PHP_CLI)
|
If none of the other answers work for you, here's an option:
There are a bunch of server monitoring services out there that will make an http call to your site at regular intervals (every minute if you like). You can get 5 minute intervals for free on some of them.
Create a password protected page, that performs your function (if it hasn't been done yet today) and point that service at it.
At least this way you won't have to write anything additional, and you can rest easy knowing it doesn't rely on your home machine.
|
I'm running .NET on a windows box and I would like to have a function run every night at midnight. Of course since HTTP stateless and Windows doesn't have a "cron job" type function (that I know of), I will either have to visit my site myself every night at midnight or just wait for a user to visit the site to rely on it being updated.
Is there an alternative to this that I can create where something will automatically run at a certain time?
|
How to emulate cron jobs on a Windows Server?
|
I do use cron and its types:
npm i cron
npm i -D @types/cron
Since there are types available it works pretty fine with TypeScript. In my TypeScript I do something like:
import { CronJob } from 'cron';
class Foo {
cronJob: CronJob;
constructor() {
this.cronJob = new CronJob('0 0 5 * * *', async () => {
try {
await this.bar();
} catch (e) {
console.error(e);
}
});
// Start job
if (!this.cronJob.running) {
this.cronJob.start();
}
}
async function bar(): Promise<void> {
// Do some task
}
}
const foo = new Foo();
Of course there is no need to start the job inside the constructor of Foo. It is just an example.
|
In Typescript, I have a controller class that has a method that I want to run daily at 5am.
My first thought was to schedule something using node-cron or node-scheduler, but these seem to be strictly for node projects, not typescript.
What I need to happen is a) transpile my entire typescript project into node and then b) Run the method as scheduled.
There doesn't seem to be any explanation on how to do this though. The explanations I do see are all about running a node.js function on some schedule, such as this one:
I need a Nodejs scheduler that allows for tasks at different intervals
The below code illustrates my best approximation at what I'm trying to do.
controller.ts
import SomeOtherClass from './factory';
class MyController {
public async methodToRun(){
console.log ("King Chronos")
}
}
cron-job.ts
import MyController from "../src/controller";
let controller = new MyController();
var cronJob = require('cron').CronJob;
var myJob = new cronJob('00 30 11 * * 1-5', function(){
controller.methodToRun();
console.log("cron ran")
});
myJob.start();
|
How to make a Cron job for a typescript class method
|
Ok, after several hours I found the solution:
The user root was running the script but AWS was not configured for this user. I only needed to configure AWS for the user root:
# aws configure
|
I have this script:
#!/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games
SHELL=/bin/bash
# Create EBS Data snapshot
/usr/local/bin/aws ec2 create-snapshot --volume-id "vol-XXXXX" --description "test"
It works perfectly if I run it from the shell, but does nothing with Cron. Why? I am using IAM roles, is it important?
|
AWS CLI not working with cron
|
17
create a shell script
eg scripts.sh
#!/bin/bash
source /home/user/MYVENV/bin/activate
python /path/to/file/script.py
Then in cron put
*/1 * * * * bash /path/to/shell/script/scripts.sh
The script will load all your environment variables and execute from the python in your environment
Share
Improve this answer
Follow
answered Jun 27, 2019 at 14:37
PiakkaaPiakkaa
77866 silver badges1313 bronze badges
Add a comment
|
|
Usually I SSH into my EC2 instance and run:
source MYVENV/bin/activate
How do I set my cronjob to activate the virtual environment? My Django script requires ENVIRONMENT variables that are stores in ~/.bash_profile
I tried following the steps here to no avail
Cron and virtualenv
SHELL=/bin/bash
*/1 * * * * root source /home/ec2-user/MYVENV/activate && python /home/script.py
This is my current setup above.
I get this following error in the log:
/bin/bash: root: command not found
|
How do I run a cronjob with a python virtual environment?
|
18
Using the job-dsl syntax:
triggers {
cron('13 20 * * 0,1,2,3,4,5,6 \n 13 8 * * 0,1,2,3,4,5,6')
}
From the job-dsl documentation:
To configure a multi-line entry, use a single trigger string with
entries separated by \n.
https://jenkinsci.github.io/job-dsl-plugin/#path/freeStyleJob-triggers-cron
Share
Improve this answer
Follow
answered Mar 2, 2018 at 3:29
edstedst
1,09411 gold badge1010 silver badges2020 bronze badges
Add a comment
|
|
In a Jenkins job config's Build Triggers section, it is possible to add multiple cron expressions separated on each line in the Schedule textarea e.g:
13 20 * * 0,1,2,3,4,5,6
13 8 * * 0,1,2,3,4,5,6
https://stackoverflow.com/a/44209349/1291886
How would one do this using the job-dsl/pipeline syntax?
|
Multiple cron expressions using the job-dsl/pipeline syntax
|
Now I check whether the process is running by ps and warp the php script by a bash script:
#!/bin/bash
PIDS=`ps aux | grep onlytask.php | grep -v grep`
if [ -z "$PIDS" ]; then
echo "Starting onlytask.php ..."
php /usr/local/src/onlytask.php >> /var/log/onlytask.log &
else
echo "onlytask.php already running."
fi
and run the bash script by cron every minute.
|
Currently, I tried to prevent an onlytask.php script from running more than once:
$fp = fopen("/tmp/"."onlyme.lock", "a+");
if (flock($fp, LOCK_EX | LOCK_NB)) {
echo "task started\n";
//
while (true) {
// do something lengthy
sleep(10);
}
//
flock($fp, LOCK_UN);
} else {
echo "task already running\n";
}
fclose($fp);
and there is a cron job to execute the above script every minute:
* * * * * php /usr/local/src/onlytask.php
It works for a while. After a few day, when I do:
ps auxwww | grep onlytask
I found that there are two instances running! Not three or more, not one. I killed one of the instances. After a few days, there are two instances again.
What's wrong in the code? Are there other alternatives to limit only one instance of the onlytask.php is running?
p.s. my /tmp/ folder is not cleaned up. ls -al /tmp/*.lock show the lock file was created in day one:
-rw-r--r-- 1 root root 0 Dec 4 04:03 onlyme.lock
|
How to prevent PHP script running more than once?
|
This is absurdly late to the game, but I did find a solution to this. What was happening was:
I had originally typed up the cron commands in Windows Notepad and uploaded them. Apparently what was happening was a carriage return ("/r", IIRC) was getting plugged in, unbeknownst to me (and vim, when I viewed the file from putty.) A friend removed those carriage returns by a method I don't recall/did not follow too well unfortunately, but after the returns were removed, it all worked.
|
I've spent a solid day looking for a solution to this specific situation (on Stack Overflow and the Googs,) so I do apologize if this is already on Stack Overflow.
I'm trying to set up a fairly simple cron job in AWS via the command line:
* * * * * /usr/bin/php /opt/app/current/record_user_login.php
The cron job successfully fires and is able to touch the file in question (it is hitting the correct environment.) However, I keep getting the error:
"Could not open input file"
I've:
chmod'd the file to 777
Changed the script to just echo "Hello world"
Tried initiating the cronjob as the root user
chmod'd the crontab file itself to 777
None of these solutions seem to work. For a yet unknown reason, I can't edit rsyslog.conf to turn on cronlog, so I don't have any data from that.
The contents of record_user_login are:
<?
include("connect_to_mysql.php");
//Logged in in 1 week
$current_date = date('Y-m-j H:i:s', strtotime("-1 weeks"));
$query = "SELECT DISTINCT user_id FROM users_login_history WHERE sign_in_time > '$current_date'";
$result = mysql_query($query) or die(mysql_error());
$i = 0;
while($row = mysql_fetch_array($result)){
$i++;
}
$query = "INSERT INTO sqm_data (feature, action) VALUES ('user login', $i)";
if(!mysql_query($query)) {
die('Error: ' . mysql_error());
}
?>
Any ideas?
|
Cron Job error "Could not open input file"
|
From documentation of CronJobs and Jobs
A Cron Job creates Jobs on a time-based schedule
...
A job creates one or more pods and ensures that a specified number of them successfully terminate.
All you need is to view logs for a pod that was created for the job.
Find your job with kubectl get jobs. This will return your CronJob name with a timestamp
Find pod for executed job kubectl get pods -l job-name=your-job-@timestamp
Use kubectl logs your-job-@timestamp-id to view logs
Here's an example of bash script that does all the above and outputs logs for every job's pod.
jobs=( $(kubectl get jobs --no-headers -o custom-columns=":metadata.name") )
for job in "${jobs[@]}"
do
pod=$(kubectl get pods -l job-name=$job --no-headers -o custom-columns=":metadata.name")
kubectl logs $pod
done
|
Seems that kubectl logs doesn't support cronjob. It says
error: cannot get the logs from *v1beta1.CronJob: selector for *v1beta1.CronJob not implemented
Currently I check the logs of all relative jobs one by one.
Is there any simple command or tool to get these logs?
I did some research on bash script and modified edbighead's answer to better suit my needs.
# cronJobGetAllLogs.sh: Get all logs of a cronjob.
# example:
# ./cronJobGetAllLogs.sh [Insert name of cronJob]
jobs=( $(kubectl get jobs --no-headers -o custom-columns=":metadata.name" | awk "/$1-[0-9]+/{print \$1}" | sort -r ) )
for job in "${jobs[@]}"
do
echo Logs from job $job
pod=$(kubectl get pods -l job-name=$job --no-headers -o custom-columns=":metadata.name")
kubectl logs $pod
done
# cronJobGetLatestLog.sh: Get log of latest job initiated by a cronjob.
# example:
# ./cronJobGetLateestLog.sh [Insert name of cronJob]
job=$(kubectl get jobs --no-headers -o custom-columns=":metadata.name" | awk "/$1-[0-9]+/{print \$1}" | sort -r | head -1)
pod=$(kubectl get pods -l job-name=$job --no-headers -o custom-columns=":metadata.name")
kubectl logs $pod
|
How to get logs of jobs created by a cronjob?
|
The problem is that the environment isn't what you expect.
You don't say whether the cron is running as your user, or as root, but, in either case, you can test to see what the environment looks like by adding another cron entry of:
* * * * * /usr/bin/env > /path/to/your/home/directory/env.txt
Let that run once, then pull it out, and look at the file.
Instead of using /usr/bin/env to try to find a Ruby to run your code, define the Ruby explicitly:
* * * * * /path/to/the/ruby/you/want /usr/local/src/hello/hello.rb >> /usr/local/src/hello/hello.log 2>&1
You can figure out which Ruby you want by using:
which ruby
Alternately, instead of relying on /usr/bin/env in your #! line, define your Ruby there.
Using /usr/bin/env ruby in your code is a convenience when you're using something like RVM or rbenv, and switching between versions of Ruby. It's not a good choice when you're putting something into "production", whether it's on your machine in your own account, or on a production host running as root.
If you are on Linux or Mac OS, try man 5 crontab for more information. Also, "Where can I set environment variables that crontab will use?" should be very useful.
|
I have a simple ruby script, hello.rb:
#!/usr/bin/env ruby
puts 'hello'
It runs ok at the command line:
# /usr/local/src/hello/hello.rb
hello
However, if I put it in cron:
* * * * * /usr/local/src/hello/hello.rb >> /usr/local/src/hello/hello.log 2>&1
There are errors in the log file:
/usr/bin/env: ruby: No such file or directory
/usr/bin/env: ruby: No such file or directory
...
/usr/bin/env: ruby: No such file or directory
/usr/bin/env ruby runs ok at command line though:
# /usr/bin/env ruby -v
ruby 1.8.7 (2012-10-12 patchlevel 371) [i686-linux]
How to fix the env error for cron?
|
#!/usr/bin/env ruby is not found in cron
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.