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");
}
Related
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
I've read through the available q and a on SO, but nothing I have found answers my question of how to format my time in 12hour format.
Following is my code that runs a query on a MySQL database and returns results, checking to see if an appointment is within 15 minutes of login so an alert can pop.
public void apptCheck(int userId) throws SQLException {
// this method checks for an appointment occurring within 15 minutes of login
Statement apptStatement = DBQuery.getStatement();
String apptQuery = "Select apt.start, cs.customerName from DBName.appointment apt "
+ "JOIN DBName.customer cs ON cs.customerId = apt.customerId WHERE "
+ "userId = " + userId + " AND start >= NOW() AND start < NOW() + interval 16 minute";
apptStatement.execute(apptQuery);
ResultSet apptRs = apptStatement.getResultSet();
while(apptRs.next()) {
Timestamp apptTime = apptRs.getTimestamp("start");
ResourceBundle languageRB = ResourceBundle.getBundle("wgucms/RB", Locale.getDefault());
Alert apptCheck = new Alert(AlertType.INFORMATION);
apptCheck.setHeaderText(null);
apptCheck.setContentText(languageRB.getString("apptSoon") + " " + apptTime.toInstant().atZone(ZoneId.systemDefault()));
apptCheck.showAndWait();
}
My result is:
I want the time to display 3:00, not the 19:00 - 06:00. How can I make that happen?
ZonedDateTime zonedDateTime=ZonedDateTime.of(apptTime.toLocalDateTime(),ZoneId.systemDefault());
You can use ZonedDateTime and format the time as you want.
docs.oracle.com/javase/8/docs/api/java/time/ZonedDateTime.html ZonedDateTime has a lot of features you can see all here and you can get the hour, minute, day etc.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("hh:mm:ss");
String formattedString = zonedDateTime.format(formatter);
if you only want time in 12hour format you can use this
I found the solution which will perform the UTC to local time conversion and then format the time so that the resulting alert is in 12 hour time format without the date or time zone info. Here is the full code:
while(apptRs.next()) {
Timestamp apptTime = apptRs.getTimestamp("start");
// perform time conversion from UTC to User Local Time
ZoneId zidApptTime = ZoneId.systemDefault();
ZonedDateTime newZDTApptTime = apptTime.toLocalDateTime().atZone(ZoneId.of("UTC"));
ZonedDateTime convertedApptTime = newZDTApptTime.withZoneSameInstant(zidApptTime);
ResourceBundle languageRB = ResourceBundle.getBundle("wgucms/RB", Locale.getDefault());
Alert apptCheck = new Alert(AlertType.INFORMATION);
apptCheck.setHeaderText(null);
// set the Alert text and format in 12 hour format
apptCheck.setContentText(languageRB.getString("apptSoon") +
convertedApptTime.toInstant().atZone(ZoneId.systemDefault())
.format(DateTimeFormatter.ofPattern("h:mm a")) + ".");
apptCheck.showAndWait();
}
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.
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.
Please post any smarty syntax to Get number of days between two dates from my database. i was to able to display all the other fields,but this date field with number of days not working as the way i was expected.Please let me know is there any way to get this solution without any smarty additional plugins.
Smarty does not include any specific functions for doing date math operations. They have the date_format for timestamps, but otherwise you'd either have to write your own days_diff plugin, find one online, or do the date math in PHP and assign to a new variable in Smarty.
Here is my function for this problem:
/*
* Smarty plugin
* -------------------------------------------------------------
* Type: function
* Name: date_diff
* Author: RafaĆ Pawlukiewicz
* Purpose: factor difference between two dates in days, weeks, or years
* Input: d1 = "mm/dd/yyyy" or "yyyy/mm/dd" or "yyyy-mm-dd"
* d2 = "mm/dd/yyyy" or "yyyy/mm/dd" or "yyyy-mm-dd" or $smarty.now
* assign = name of variable to assign difference to
* interval = "days" (default), "weeks", "years"
* Examples: {date_diff d1="2020-01-20"}
* Examples: {date_diff d1="2020-01-20" d2=2020-02-10 interval="weeks"}
* Examples: {date_diff d1="2020-01-20" d2=2020-02-10 assign="variable_diff"} result: {$variable_diff}
* -------------------------------------------------------------
*/
function smarty_function_date_diff($params, &$smarty)
{
$d1 = isset($params['d1']) ? $params['d1'] : date('Y-m-d');
$d2 = isset($params['d2']) ? $params['d2'] : date('Y-m-d');
$assign_name = isset($params['assign']) ? $params['assign'] : '';
$date1 = strtotime($d1);
$date2 = strtotime($d2);
// use current for empty string
if (! $date1) {
$date1 = date('Y-m-d');
}
if (! $date2) {
$date2 = date('Y-m-d');
}
$interval = isset($params['interval']) ? $params['interval'] : 'days';
// diff in days
$diff = ($date2 - $date1) / 60 / 60 / 24;
if ($interval === "weeks") {
$diff /= 7;
}
elseif ($interval === "years") {
$diff /= 365.25;
}
$diff = floor($diff);
if ($assign_name) {
$smarty->assign($assign_name, $diff);
}
else {
return $diff;
}
}