I have a JUnit test that looks for a user that hasn't changed their password in the past 355 days. In the test, I save a user with their last password update date to the system's date/time - 355 days. Then I run the function that should pick up that user for additional processing.
The test passes locally, both when the test is run on its own AND when the entire test suite is run. However, for some reason, the test fails between 12 - 1pm when deploying our code in Jenkins. It's not a consistent failure, either. Sometimes, simply running the deployment again with no changes allows the test to succeed. What could be causing this issue?
For reference, the test looks like:
#Test
public void passwordExpiryTest() {
Timestamp currentTimeMinus355Days = new Timestamp(System.currentTimeMillis() - 30672000000L);
createUser("expiringUser", currentTimeMinus355Days);
createUser("recentUser", new Timestamp(System.currentTimeMillis() - 864000000L));
List<User> passwordExpiringUsers = userDao.getUsersWithPasswordExpiringInTenDays();
Assert.assertEquals(1, passwordExpiringUsers.size());
}
And userDao.getUsersWithPasswordExpiringInTenDays is a SQL query (into a Postgres table):
SELECT * FROM users WHERE last_password_update IS NOT NULL AND EXTRACT(epoch FROM (NOW() - last_password_update))/86400 >= 355 AND EXTRACT(epoch FROM (NOW() - last_password_update))/86400 <= 356")
I would investigate the logic in userDao.getUsersWithPasswordExpiringInTenDays(). The concept of a "day" depends on an interpretation - is it 24 hours, or the next day number (e.g. 11 vs 12 of April?)? And is there an impact of time zones? e.g. are you testing in India, but the server lives in the US (12 hours time difference?)
Related
What I want to do
I am creating two batch processes using #Scheduled function of Spring Boot by kotlin.
batch to retrieve data running at 00:00 a.m. (Japan time) every day
batch to integrate data running at 03:00 a.m. (Japan time) every day
Problems
I was able to confirm from the log that the batch executed at 00:00 worked correctly, but I was unable to confirm the execution of batch 2.
The source code in question
The following is the application code.
#Service
class ScheduledTaskService {
#Scheduled(cron = "\${task.fetch-data.cron}", zone = "\${task.fetch-data.zone}")
fun fetchData() {
println("The time is now " + ZonedDateTime.now(ZoneId.of("Asia/Tokyo")).toString())
println("start to fetch data")
}
#Scheduled(cron = "\${task.integrate-data.cron}", zone = "\${task.integrate-data.zone}")
fun integrateData() {
println("The time is now " + ZonedDateTime.now(ZoneId.of("Asia/Tokyo")).toString())
println("start to integrate data")
}
}
The following is the application.yml
task:
fetch-data:
cron: ${TASK_FETCH_DATA_CRON:0 0 0 * * *}
zone: ${TASK_FETCH_DATA_ZONE:Asia/Tokyo}
integrate-data:
cron: ${TASK_INTEGRATE_DATA_CRON:0 0 3 * * *}
zone: ${TASK_INTEGRATE_DATA_ZONE:Asia/Tokyo}
I also added #EnableScheduling to the main class.
#SpringBootApplication
#EnableTransactionManagement
#ConfigurationPropertiesScan
#EnableScheduling
class APIApplication(private val apiConfig: APIConfig) : ApplicationListener<ApplicationReadyEvent> {
...
Things I tried
Verified at different times
Batch 1: 11:00 AM
Batch 2: 12:00 PM
Result: batch 1 worked, batch 2 did not.
Set the execution timing of 2 to 1 minute after 1
Batch 1: 12:20 PM
Batch 2: 12:21 PM
Result: both 1 and 2 worked.
Change the execution timing of 1 and 2 to 2->1 order
Batch 1: 14:30 PM
Batch 2: 14:05 PM
Result: batch 2 worked, batch 1 did not.
I am currently investigating the possibility that the results may vary depending on the time between when the server is started and when the batch is executed.
If you have any ideas, I'd love to hear them.
Additional information (FW/tool version, etc.)
PC: macOS Big Sur 2.5GHz quad-core Intel Core i7 with 16GM memory
Project SDK: Java 11 (Amazon correto)
Spring Boot version: 2.2.4.RELEASE
Editor: IntelliJ
Your cron looks a bit off. #Scheduled spring uses Spring Cron.
Your cron expression should be
Midnight: "0 0 0 * * *". You can also use #midnight here.
3AM: "0 0 3 * * *"
I am trying to find out the time spent on each tab/website by the user.
For example if I visited youtube and watched it for 10 minutes then I should be able to see something like this
www.youtube.com ---> 10 minutes
I already made a connection with sqlite database i.e. History file present in chrome directory and was able to run the following sql command to fetch the data:
SELECT urls.id, urls.url, urls.title, urls.visit_count, urls.typed_count, urls.last_visit_time, urls.hidden, urls.favicon_id, visits.visit_time, visits.from_visit, visits.visit_duration, visits.transition, visit_source.source FROM urls JOIN visits ON urls.id = visits.url LEFT JOIN visit_source ON visits.id = visit_source.id
So can anyone tell me which combination of column can i use to get the time spent on each website.
Please note that: visit_duration is not giving me appropriate data.
visit_duration Stores duration in microseconds, you need to convert and format that number. Here is one way to show a human-readable visit duration:
SELECT urls.url AS URL, (visits.visit_duration / 3600 / 1000000) || ' hours ' || strftime('%M minutes %S seconds', visits.visit_duration / 1000000 / 86400.0) AS Duration
FROM urls LEFT JOIN visits ON urls.id = visits.url
Here is a sample output:
URL
Duration
http://www.stackoverflow.com/
3 hours 14 minutes 15 seconds
You can also use strftime if you want more format options
I have job that will run every 10 mins. I don't want to use Spring Scheduler based on last job run next job will schedule to run. Suppose First job ran at 10:15 AM, Subsequent job needs to run at 10:25 AM. When i googled i saw posts with nextExecutionTime. When i use nextExecutionTime my subsequent job is running at 10:20 instead of 10:25. Below is my code, Can any one give an idea how i can run my job at exact 10 mins from last run.
CronTrigger trigger = new CronTrigger("0 0/10 * * * ?");
SimpleTriggerContext triggerContext = new SimpleTriggerContext();
triggerContext.update(Date.from(ZonedDateTime.now().toInstant()), Date.from(ZonedDateTime.now().toInstant()), Date.from(ZonedDateTime.now().toInstant()));
Date nextFireAt = trigger.nextExecutionTime(triggerContext);
System.out.println(nextFireAt);
Can you try the below. I provide below the sequence.
Get the date now.
Add 10 mins to the date and get a new updated date
Update the like triggerContext.update(null, null, date in which you have added 10 mins);
I am working on a django and java project in which I need to compare the time in django to the time in current time in java.
I am storing the enbled_time in models as :
enabled_time = models.DateTimeField(auto_now = True, default=timezone.now())
The time gets populated in the db in the form :
2017-02-26 14:54:02
Now in my java project a cron is running which checks whether enabled_time plus an expiry time is greater than the current time something as:
Long EditedTime = db.getEnabledTime() + (expiryTime*60*1000); //expiryTime is in mins
if (System.currentTimeMillis() - EditedTime > 0) {
//do something
}
Here db is the database entity for that table.
But db.getEnabledTime() gives a result '2017'. What am I doing wrong?
PS: I am storing time as Long which seems unsuitable to me. Can someone suggest which datatype should I choose or does it work fine?
I've been trying to figure out this bug for few days. I have narrowed the issue down to a test case as follows. Again, this is a test case that causes the bug to happen. The function (at this point) is not a practical one, but just trying to figure out the bug.
Server is running:
- Tomcat 6
- OpenJDK 1.6.0_17
- CentOS 5.5
I have a simple Class file with the following method Static Method and Static variable declaration:
public static java.text.SimpleDateFormat displayDateSDF1 = new java.text.SimpleDateFormat("MM/dd/yyyy");
public static java.util.Date getSubDateMini(String inputDate)
{
java.util.Date testObj = null;
try
{
testObj = displayDateSDF1.parse("01/01/2000") ;
}
catch (Exception e)
{
}
return testObj;
}
Testing in Tomcat:
When I run this method, I'd expect to get the same result every time, right? However, if I call this method from a JSP, I get the expected result of a Date object with value 1/1/2000 about 99.9% of the time. However, sometimes I get an unexpected data object passed back with a seemingly random date value.
To test this, I created a JSP with the following code segment in it:
for (int i=0; i<200000;i++)
{
java.util.Date testObjLib = TestDate.getSubDateMini("") ;
if (testObjLib!=null&&!testObjLib.toString().equalsIgnoreCase("Sat Jan 01 00:00:00 PST 2000"))
{
out.print("<br>"+testObjLib+"");
}
}
Some dates that appear are as follows:
Wed Jan 01 00:00:00 PST 1
Fri Aug 01 00:00:00 PDT 2166
In 200,000 runs, I get approximately 50 bad dates which gives an error rate of ~0.025% but again it's random. I've run this loop with 10 iterations and received an error. Sometimes it runs the loop with 200,000 and all dates look good.
Testing in Java:
Running this loop via a console/terminal app in CentOS with the same loop, I have not seen this error happen yet. I increased the loop to 10,000,000 and had no false results as of yet.
I can understand out of memory or some thrown error (which would result in a null value) but not corrupt/inconsistent data. I built up a new server from scratch with Tomcat 6 and also tried Tomcat 5.5 and both have the same results. I have not tried Tomcat 7.
Any suggestions?
SimpleDateFormat is not thread-safe.
This means that when it is accessed from multiple threads, unexpected results can be observed. And tomcat is serving each request from a separate thread, so whenever two requests are made at the same time, the problem would arise.
You have a number of options:
instantiate the SimpleDateFormat on each call of the method (rather than making it static)
if you need the format more than once per thread, use a ThreadLocal to store it.
alternatively use joda-time, where DateTimeFormat is thread-safe.