can't understand quartz schedule expression - spring

Spring quartz schedule expression
0 40 4-16 * * *
Java spring scheduler quartz
I have old code with express schedule="0 40 4-16 * * *" i do not understand what does that mean ?
Even after readying the following file can't figure out what does above Cron expression do. http://en.wikipedia.org/wiki/Cron

It will run every day on 4:40, 5:40, 6:40, ... 16:40. Simple test code:
import org.springframework.scheduling.support.CronSequenceGenerator;
CronSequenceGenerator cron = new CronSequenceGenerator("0 40 4-16 * * *", TimeZone.getDefault());
Date d = new Date();
for (int i = 0; i < 20; ++i) {
d = cron.next(d);
System.out.println(d);
}
or this for Quartz API.

Related

Cron expression in Spring, validation?

So I need a Cron expression which will run my service in following interval:
-every 2h;
-during work hours 9-17h;
-only on work days MON-FRI;
-every month;
-of every year;
I've come up with this:
#Scheduled(* * 0/2 * * MON-FRI)
public Object updateDB() {
controllerImpl.updateDB();
return new Object();
}
I think the problem here s every 2 hours between 9-17h, isn't it?
Try this:
#Scheduled(* * 9-17/2 * * MON-FRI)
You can try following cron expression:
#Scheduled(* * 9-17/2 ? * MON-FRI)
For future references you can use following to create your cron expression:
https://www.freeformatter.com/cron-expression-generator-quartz.html

Get Stage View Times for Current Build

Is it possible to get the stage view time values programatically?
I would like to print within the console the stage times for all the stages including the stage titles.
Something like:
Build Code: 19s
Unit Tests: 7s
Integration Tests: 17s
Looking at the plugin code I can see how it's rendered through the formatter, but I can't figure out how I could access those values through a Jenkinsfile.
In the source code it looks like millisecond time is being used. I can convert that easily to better human readable time.
/**
* Calculate how long something took from start to end
* #param start Start time in milliseconds
* #param end End Time in milliseconds
* #return Duration as String from start to end
*/
def calculateDuration(start, end) {
long elapsedTime = end - start
Long second = (elapsedTime / 1000).longValue() % 60;
Long minute = (elapsedTime / (1000 * 60)).longValue() % 60;
Long hour = (elapsedTime / (1000 * 60 * 60)).longValue() % 24;
Long remainderMillis = elapsedTime % 1000
return "${hour}h ${minute}m ${second}s ${remainderMillis}ms"
}
So this isn't going to be the super easy solution you're looking for, but I didn't know how to do this either and wanted to try.
Basically I'm writing simple HTML to a file at the OS level, and at the end publishing it via the Rich Text Publisher plugin. It then displays on the build page.
I'm not sure how to properly format the duration into hh:mm:ss
def logit(logMessage) {
logFile.append(logMessage + "\n")
}
def calculateDuration(start, end) {
long elapsedTime = end - start
Long second = (elapsedTime / 1000).longValue() % 60;
Long minute = (elapsedTime / (1000 * 60)).longValue() % 60;
Long hour = (elapsedTime / (1000 * 60 * 60)).longValue() % 24;
Long remainderMillis = elapsedTime % 1000
return "${hour}h ${minute}m ${second}s ${remainderMillis}ms"
}
node () {
stage('Create logfile') {
sh "rm -f /tmp/log.html"
logFile = new File("/tmp/log.html")
logit("<html>")
logit(" <body>")
}
stage('Time this stage') {
start = System.currentTimeMillis()
logit("Start time " + start + "<br>")
sleep(3)
end = System.currentTimeMillis()
logit("End time " + end + "<br>")
dur = calculateDuration(start, end)
println "Duration: " + dur
logit("Duration: " + dur + "<br>")
}
stage('Publish') {
logit(" </body>")
logit("</html>")
rtp (nullAction: '1', stableText: '${FILE:/tmp/log.html}')
}
}
Ironically, years later I have discovered a better solution that gives me exactly what I needed, which was the time by stage.
Depending on the type of Jenkins job, Freeestyle or Multibranch you can look at the exposed Jenkins API endpoints to get the information.
Freestyle Endpoint: env.BUILD_URL/api/json?pretty=true
Multibranch endpoint: env.BUILD_URL/wfapi/describe
It's a JSON response, so it's easy to parse and store by using readJSON Jenkins DSL.
Below you can see an example response for a freestyle job. Sorry for the blackout but didn't want to expose corporate dir structures.

Time comparison in html using NGIF Condition - Angular

I am in requirement for solution where I have one Admin posts application for an Android app. I have placed a delete button for post. The requirement is that delete button must be shown for 5 minutes from time of posting.
Here is the ngif condition which I have used..
*ngIf="((((post.CreatedDate | date:'dd/MM/yyyy') == (PresentDate | date:'dd/MM/yyyy')) && ((post.CreatedDate | date:'HH') == (post.CreatedDate | date:'HH')))&&((post.CreatedDate | date:'mm')< (time)))"
Code in TS page for present time + 5 minutes
const d: Date = new Date();
this.PresentDate = d;
var x = new Date();
d.getHours(); // => 9
d.getMinutes(); // => 30
this.time = d.getMinutes() +5;
this.hours = d.getHours();
Please help with the solution
Long expression in html is not good practice.
*ngIf="canDeletePost(post)"
canDeletePost(post) {
return Date.now() - post.CreatedDate.getTime() < 5 * 60 * 1000;
}
If CreatedDate is Js date. 5 * 60 * 1000 - 5 min in milliseconds. Actually, have a method in ngIf is not good practice also.
Anyway, you don't need date pipe. Pipes is used for changing view.

How to identify cron entry in spring is applicable today?

i have a list of cron entries in my database which has only values for date,day of month,day of week.
Sample cron values in my database.
"0 0 * * * "
" * * 15 2 "
" * * * * MON-FRI"
How i do check if there are any cron entry in my database that is applicable for today?i have to use this in my java spring boot application.
You can use cronexpression of quartz to get for next valid fire date of cron.
Ex.
String orgTimeZone = "US/Eastern";
String cron = "0 10 2 ? * MON,WED *";
CronExpression exp = new CronExpression(cron);
exp.setTimeZone(TimeZone.getTimeZone(orgTimeZone));
Date date = new Date();
Date nextValidFireTime = exp.getNextValidTimeAfter(date);
ZonedDateTime nextExecDate = zonedDateTimeConverter.toZonedDateTime(nextValidFireTime, orgTimeZone);
ZonedDateTime currentDate = zonedDateTimeConverter.toZonedDateTime(date, orgTimeZone);
System.out.println(nextExecDate);
ZonedDateTime after1Hourdate = currentDate.plusHours(1);
System.out.println(currentDate + ":" + after1Hourdate);
if (nextExecDate.isAfter(currentDate) && nextExecDate.isBefore(after1Hourdate)) {
System.out.println("Match Cron");
}

laravel schedule command at random time

I've got a strange issue.
I use a custom command to share, via FB api, some url.
Now this command is scheduled to a fixed cron configuration but I would like this to be randomic, maybe between time ranges.
I tried using a random sleep function inside command, but I got strange behavior.
Did anyone already have to face this problem?
One solution is to put the code you want to run into a Queued Job, and then delay that job a random amount. For example, this code will run at a random time every hour (the same can easily be extrapolated to random time every day or on some other interval):
$schedule
->call(function () {
$job = new SomeQueuedJob();
// Do it at some random time in the next hour.
$job->delay(rand(0, 60 * 59));
dispatch($job);
})
->hourly();
You can generate random time at beginning.
protected function schedule(Schedule $schedule)
{
$expression = \Cache::get('schedule:expressions:inspire');
if (!$expression) {
$randomMinute = random_int(0, 59);
// hour between 8:00 and 19:00
$hourRange = range(8, 19);
shuffle($hourRange);
// execute twice a day
$randomHours = array_slice($hourRange, 0, 2);
$expression = $randomMinute . ' ' . implode($randomHours, ',') . ' * * * *';
\Cache::put('schedule:expressions:inspire', $expression, Carbon::now()->endOfDay());
}
$schedule->command('inspire')->cron($expression);
}

Resources