Java Scheduling task - java

I am developing a spring mvc project where a notification will send to user mobile.User will select a datetime at format 'yyyy-MM-dd HH:mm' from frontend and save it to the database.when system time reach that time a notification will be send to the user mobile .
I created scheduler like this
#Component
public class NotificationScheduler extends BaseService {
#Scheduled(fixedRate = 300000)
public void sendNotification() {
Date currentDate = new Date();
System.err.println("HHHHHHHHHKKKKKK");
List<ImageInfo> listImageInfo = imageInfoDao.getImageOfParticularDate(currentDate);
}
}
this is my dao function which run a wuery to database
public List getImageOfParticularDate(Date date) {
session = getSession();
session.beginTransaction();
List<ImageInfo> imageInfoList = session.createQuery("select img from ImageInfo img where img.publishedTime =:publishedTime ").setParameter("publishedTime", date).list();
session.getTransaction().commit();
return imageInfoList;
}
this code is checking repeatedly at 5 min interval whether system time equal to publish time.if it is equal then a notification will be sent.I used Date type in model and Date type column in database. I want to know my approach is right or wrong because i can not get desire output.

Why don't you use a debug mode? Change, your the time rate you use in order to not wait too much, but I think you could determine that yourself, could you?

Related

Java LocalDate is stored as a semi-random number of days back when saved to MySQL database

I have an issue with saving correct Java LocalDates to a MySQL database. When I log the date, it shows the correct date, but when I save it for two different entities (User and Household),
Household always saves it as one day earlier (consistent and explainable by timezone diff), but
User saves a semi-random different date which I don't understand.
See image for examples of the correct date, household saved dat, user saved date and number of days difference between the user and household date can be seen in the following table. For the date 2017-04-01, the "random" version for the User entity even differs.
The dates are correct when running locally on my MacBook Pro, but the date differences occur in our Java 11 Google App Engine development or production environments. Could you help me understand why this is happening?
The date is received using a REST webservice that accepts a date as a ISO-formatted YYYY-MM-DD string as part of a UserRegistrationCommand class. This class then converts the string to a LocalDate object in its getMoveInDate method:
public class UserRegistrationCommand {
...
public String moveInDate;
...
public LocalDate getMoveInDate() {
if(moveInDate == null) {
return null;
}
try {
return LocalDate.parse(moveInDate, DateTimeFormatter.ISO_LOCAL_DATE);
} catch (Exception e) {
return null;
}
}
}
Using Spring JPA, I then save this date for an User and Household entity respectively to a MySQL database where the tables for these entities are using a DATE datatype.
When I log the date prior to saving, it shows the correct value. But when the date is saved in the database, the User table gets a date many days off, while the Household table gets a date that is one day prior to the submitted date.
(The dates in the code comments below refer to the first date example in my image)
Saving the User entity:
#Transactional
public User createUser(String email, String password, String firstName, String lastName, String language, Household household, LocalDate moveInDate, String redirectState) {
LOG.debug("Registering user {}, {}, moveInDate: {}", email, household, moveInDate != null ? moveInDate.toString() : "null"); // <-- Logs "Registering user ... moveInDate: 2017-08-01 ..."
[...]
Locale locale = localeProvider.matchAvailableLocale(language);
User user = new User(email, encodedPassword, firstName, lastName, locale, household, moveInDate, NotificationPreferences.defaultPreferences());
user.setRedirectState(redirectState);
Image profilePicture = avatarService.createProfilePicture(user.getNameInitials());
user.setProfilePicture(profilePicture);
return save(user); // <-- calls userRepository.save(user), but date is stored as 2017-07-27
}
Saving the household entity:
LOGGER.debug("ActivationCodeRegistrationStrategy.register: Setting moveInDate {} for household {} for user {}", cmd.getMoveInDate(), activationCode.getHousehold(), cmd.email); <-- logs "ActivationCodeRegistrationStrategy.register: Setting moveInDate 2017-08-01 ..."
householdService.setMoveInDate(activationCode.getHousehold(), cmd.getMoveInDate()); <-- but a date of 2017-07-31 is saved.
The householdService.setMoveInDate call just sets the date for the Household entity and saves it to database:
public void setMoveInDate(Household household, LocalDate moveInDate) {
household.setMoveInDate(moveInDate);
householdRepository.save(household);
}
This issue is coming from the MySQL Connector in java. Version 8.0.19 converts the date using the JVMs timezone which results in the 1 day off problem. This is resolved in the 8.0.20 patch. Read here https://dev.mysql.com/doc/relnotes/connector-j/8.0/en/
or you should change MySQL Connector as latest like now 8.0.28

All of my data points are lost when InfluxDB restarts

A cron job is being used to fire this script off once a day. When the script runs it seems to work as expected. The code builds a map, iterates over that map, creates points which are added to a batch, and finally writes those batched points to influxDB. I can connect to the influxDB and I can query my database and see that the points were added. I am using influxdb-java 2.2.
The issue that I am having is that when influxDB is restarted all of my data is being removed. The database still exists and the series still exists, however, all of the points/rows are gone (Each table is empty). My database is not the only database, there are several others, those databases are restored correctly. My guess is that the transaction is not being finalized. I am not aware of a way to make it do a flush and ensure that my points are persisted. I tried to adding:
influxDB.write(batchPoints);
influxDB.disableBatch(); // calls this.batchProcessor.flush() in InfluxDBImpl.java
This was an attempt to force a flush but this didn't work as expected. I am using influxDB 0.13.X
InfluxDB influxDB = InfluxDBFactory.connect(host, user, pass);
String dbName = "dataName";
influxDB.createDatabase(dbName);
BatchPoints batchPoints = BatchPoints
.database(dbName)
.tag("async", "true")
.retentionPolicy("default")
.consistency(ConsistencyLevel.ALL)
.build();
for (Tags type: Tags.values()) {
List<LinkedHashMap<String, Object>> myList = this.trendsMap.get(type.getDisplay());
if (myList != null) {
for (LinkedHashMap<String, Object> data : myList) {
Point point = null;
long time = (long) data.get("time");
if (data.get("date").equals(this.sdf.format(new Date()))) {
time = System.currentTimeMillis();
}
point = Point.measurement(type.getDisplay())
.time(time, TimeUnit.MILLISECONDS)
.field("count", data.get("count"))
.field("date", data.get("date"))
.field("day_of_week", data.get("day_of_week"))
.field("day_of_month", data.get("day_of_month"))
.build();
batchPoints.point(point);
}
}
}
influxDB.write(batchPoints);
Can you upgrade InfluxDB to 0.11.0? There have been many important changes since then and it would be best to test against that.

Android - Create Custom Calendar with Event

I have an App which shows special Days. I want to integrate them into the calendar.
The events are static, they don't change, so I don't have to update the calendar very often.
I first thought of creating a local calendar and add the events, but new android versions (since 2.3?) seem not to support that; to implement I would have to create a Calendar Provider.
I saw this project on github: https://github.com/dschuermann/birthday-adapter. It is very complicated; its main use is adding the birthdays of the contacts to a new calendar.
There is lots of code, much of which I don't think I need. Do I really need to register to android's account manager to integrate a Calendar Provider? I just need a new Calendar with my event...
Would it be easier to take the user's default Calendar and add all the Events there? I could add some identifiers to the description, to be able to remove the events if the user doesn't want them.
Any tips, tutorials, or further readings are appreciated.
Metin Kale
You can create events in your device calendar via Intent. I think it could be useful for you.
public long addEventToCalender(ContentResolver cr, String title, String addInfo, String place, int status,
long startDate, boolean isRemind,long endDate) {
String eventUriStr = "content://com.android.calendar/events";
ContentValues event = new ContentValues();
// id, We need to choose from our mobile for primary its 1
event.put("calendar_id", 1);
event.put("title", title);
event.put("description", addInfo);
event.put("eventLocation", place);
event.put("eventTimezone", "UTC/GMT +2:00");
// For next 1hr
event.put("dtstart", startDate);
event.put("dtend", endDate);
//If it is bithday alarm or such kind (which should remind me for whole day) 0 for false, 1 for true
// values.put("allDay", 1);
// event.put("eventStatus", status);
event.put("hasAlarm", 1);
Uri eventUri = cr.insert(Uri.parse(eventUriStr), event);
long eventID = Long.parseLong(eventUri.getLastPathSegment());
if (isRemind) {
String reminderUriString = "content://com.android.calendar/reminders";
ContentValues reminderValues = new ContentValues();
reminderValues.put("event_id", eventID);
// Default value of the system. Minutes is a integer
reminderValues.put("minutes", 5);
// Alert Methods: Default(0), Alert(1), Email(2), SMS(3)
reminderValues.put("method", 1);
cr.insert(Uri.parse(reminderUriString), reminderValues); //Uri reminderUri =
}
return eventID;
}
For more information visit http://developer.android.com/reference/java/util/Calendar.html
In this reply you how to get contacts and birthdays.
Android Applicaiton - How to get birthday of a contact
and this library will offer you a powerful and flexible schedule so you can use
Caldroid Library

How do you refresh a database view when using Domino Java API?

I'm using the Domino Java API to query a database on a remote server. The server is processing the documents, and I'm trying to get their status. However, when I create the session, and run a query, even if I loop and check again every 30 seconds, my code will never see those documents update- it only sees the status at the time it created the first query. I have a few more loops, but the basic code outline is below- can someone tell me what I'm doing wrong?
Is there a way to update the current Database view from the Java API? The databases are not full text indexed, and cannot be due to outside constraints.
public static boolean queryDatabase(String adminFilePath, String targetItem)
NotesThread.sinitThread();
Session session =NotesFactory.createSession((String) null, (String) null, (String) null);
Registration Reg = s.createRegistration();
Reg.switchToID(adminFilePath, password);
DocumentCollection dc = getRecentDocsFromDB(session);
numResults=dc.getCount();
if (numResults > 0) {
//loop through documents to find what I'm looking for
//if the documents contain "done", finish, else:
Thread.sleep(60000);
session.recycle();
session=SessionFactory.newSession(adminFilePath, "password");
dc = getRecentDocsFromDB(session);
found = searchDocumentCollection(dc, targetItem);
//this is essentially doing the same thing again- create a session, get docs made in the
//past day or so, and loop through looking for the ones I need.
}
private static DocumentCollection getRecentDocsFromDB(Session session){
Database db = SessionFactory.openDatabase(session, server, database);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
DateTime dt = session.createDateTime(cal);
DocumentCollection dc = searchNotesDBUsingDate(session, db,"Form=\"event\"", dt);
}
public static DocumentCollection searchNotesDBUsingDate(Session session,
Database database, String query, DateTime dt) throws NotesException {
DocumentCollection dc = null;
dc = database.search(query, dt);
return dc;
}
I've updated the code with a session.recycle() call. (Thanks for the suggestion!) In testing, it's not having any effect- the code is working for the first document, but then never sees a second document being called.
It's insane, because it seems to be caching the session anyway!
I tried to reproduce the problem, but I wasn't able to. In my tests, Database.search() always returns the latest documents -- even if a document is added after the database is opened. I suspect there is a subtle problem in your code (perhaps what Richard Schwartz suggested in his comment).
It may or may not be relevant, but I wasn't able to compile your version of getRecentDocsFromDB() because I don't have a SessionFactory class. My version just uses Session.getDatabase() like so:
private static DocumentCollection getRecentDocsFromDB(Session session, String server, String database) throws NotesException {
Database db = session.getDatabase(server, database);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
DateTime dt = session.createDateTime(cal);
DocumentCollection dc = searchNotesDBUsingDate(session, db,"Form=\"event\"", dt);
return dc;
}
Also, as Richard mentioned, you are not reading a view. You are searching the database for all documents created (or modified) by the "event" form in the last 24 hours. And you are doing this in a tight loop. Even if you get it to work, this approach isn't the best for production. You might want to research the use of lotus.domino.View and lotus.domino.ViewNavigator.

How to save a jpa object within a for loop

I have a list of users which I would like to send invite emails to, after I send the email, i would like to save that person in a separate table so incase server goes down we won't be sending double emails since we know who was the last person we sent email to. this is the code:
#play.db.jpa.NoTransaction
public void sendInvite() {
Long lastUser = (Long) User.find("select MAX(id) from User").fetch().get(0);
Long lastId = (Long) Contact.find("select MAX(id) from Contact").fetch().get(0);
for (i=lastContacted; i < totalNumUsers; i++) {
UserContact contact = new UserContact();
contact.firstName = user.firstName;
contact.lastName = user.lastName;
contact.email = user.email;
if (validateEmail(user) == false) {
continue;
}
sendInviteEmail(user);
saveContact(contact); //THIS DOESN'T TAKE PLACE UNTIL END OF THE LOOP
Thread.sleep(2000);
}
}
The Problem is that the saved contact, is not getting saved in the database until the end of the for loop. i have tried:
contact.em().persist(contact);
contact.em().flush();
but that is not working either
* i would also want to add that the method is being run from a Job and not from a Controller.
If you do all this in a transaction, and the server goes down, the transaction won't be committed, and even if you flush during the transaction, nothing will be written to the database. Foe each and every contact, you need to open a new transaction, save the contact in this new transaction, then commit the transaction.

Categories