Sorry for my bad english.
I'm implementing Java TimerTask when creating an Android application. The code isn't to complicated. When it hit the interval, it will send an SMS & email.
I have some option with the sending SMS / email interval. 5 minutes, 15 minutes, 30 minutes, 1 hour, and 2 hour.
I tried using 5 minutes, and 15 minutes (I converted it into milis), no trouble occurred. It send sms and email every 5 / 15 minutes exactly. And I prove that i have no problem using timertask.
But, when I changed it to 30 minutes or more. my application cannot send sms / email. It looked like that the timer didn't work correctly.
Does it have any interval limitation on using Timer Task ??
this is my code snippet.
private void activateNotificationByInterval(int notificationInterval) {
timerNotificationByInterval = new Timer();
timerNotificationByInterval.schedule(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
// coba
// if (oldLatitude != childLatitude
// && oldLongitude != childLongitude) {
if ((enableSMS == true)) {
sendSMS();
}
if ((enableEmail == true)) {
GMailSender email = new GMailSender(sender, senderPassword);
try {
email.sendMail(emailSubject + childsName, SMSMessage
+ " " + childlLocation + "\nLatitude: "
+ childLatitude + "\nLongitude: "
+ childLongitude, sender, destination);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
mpv.changeLastLocation(childLatitude, childLongitude);
// buat method untuk menangkap lokasi pertama
oldLatitude = childLatitude;
oldLongitude = childLongitude;
// } else {
// System.out.println("Lokasi Lama Berpengaruh");
// }
}
}, 0, notificationInterval);
}
*notes : notificationInterval on milis (*60000)
can you tell me how to solved it ? thank you.
Use AlarmManager and there is a link here:
http://android-er.blogspot.in/2010/10/simple-example-of-alarm-service-using.html
Related
i try with this, but it is some times not working correctly..i used a while loop for loop the code. can i add some listner for this? any one can give me the correct answer for this? in need to get responce real time
while (true) {
msgList = new ArrayList<InboundMessage>();
Service.getInstance().readMessages(msgList, InboundMessage.MessageClasses.ALL);
for (InboundMessage im : msgList) {
if (last < im.getMemIndex()) {
ResultSet rs = DB.getConnection().createStatement().executeQuery("Select * From codes where code='" + im.getText() + "'");
if (rs.next()) {
ResultSet rs2 = DB.getConnection().createStatement().executeQuery("Select * From sms_log where code='" + im.getText() + "' AND tel_no='" + im.getOriginator() + "'");
if (rs2.next()) {
if (m == null) {
m = new SMSClient(1);
}
m.sendMessage(im.getOriginator(), "The Code is Already Sent... Thank You!.");
System.out.println("The Code is Already Sent... Thank You!.");
} else {
System.out.println("The Code Verified... Thank You!.");
if (m == null) {
m = new SMSClient(1);
}
m.sendMessage(im.getOriginator(), "The Code Verified... Thank You!.");
DB.getConnection().createStatement().execute("INSERT INTO sms_log (tel_no,code,status) values('" + im.getOriginator() + "','" + im.getText() + "',1)");
}
} else {
if (m == null) {
m = new SMSClient(1);
}
m.sendMessage(im.getOriginator(), "Invalid Code... Thank You!.");
System.out.println("Invalid Code... Thank You!.");
}
}
}
Thread.sleep(10000);
System.out.println("start");
}
I think IInboundMessageNotification is the interface you are looking for
public class InboundNotification implements IInboundMessageNotification {
#Override
public void process(AGateway aGateway, Message.MessageTypes messageTypes, InboundMessage inboundMessage) {
//add you logic for received messages here
}
}
Add notification class to smsLib service
Service.getInstance().setInboundMessageNotification(new InboundNotification())
From now on, process() method will be called every time your modem receives a message.
As far as I remember, smslib (version 3.5.x) does not delete received messages so it needs to be done manually
#Override
public void process(AGateway aGateway, Message.MessageTypes messageTypes, InboundMessage inboundMessage) {
try {
aGateway.deleteMessage(inboundMessage);
} catch (TimeoutException | GatewayException | InterruptedException | IOException e) {
e.printStackTrace();
}
// your logic here
}
otherwise you will keep receiving not deleted messages every time you receive a new one.
Hope you will find this useful.
Hi Guys First of all I must say thanks to all of you guys for helping me :). I was a silent member before this query and benefited a lot from other members question.
But now I'm stuck in my code. See I'm developing a software that will help EVENT MANAGEMENT. I have done all that basics of creating and saving events in the database - i'm using sqlite db.
I'm stuck for code of pop-up and alarm when event time is started.
I saved date as String in db which is in this format "26-04-2015".
I saved time as String in db which is in this format "17:00:00".
What I've tried uptil now is this - I was comparing current time with that on db but failed to make it work)
Any suggestion or help will be highly appreciated.
private void checkAlarm() {
new Thread() {
Calendar cal = new GregorianCalendar();
int hour = cal.get(Calendar.HOUR);
int min = cal.get(Calendar.MINUTE);
int sec = cal.get(Calendar.SECOND);
String time = hour + ":" + min + ":" + sec;
String[] data = connect.readData1("Select e_sdate, e_stime,e_title from tbl_event order by e_sdate ASC limit 1", "e_stime", "e_title");
String sTime = data[0];
String title = data[1];
public void run() {
while (true) {
try {
Thread.sleep(1000);
System.out.println("time from db : " + sTime);
System.out.println("time current : " + time);
} catch (Exception e) {
}
if (time.equals("sTime")) {
try {
TrayIcon icon = new TrayIcon(getIconImage(), "Event Management System", createPopupMenu());
playSound();
icon.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "This event has been started now.");
}
});
SystemTray.getSystemTray().add(icon);
Thread.sleep(3000);
icon.displayMessage("Event : " +title, "Event Time : " +sTime, TrayIcon.MessageType.INFO);
} catch (Exception e) {
System.out.println("Tray Icon Error : " +e);
}
}
}
}
}.start();
}
I have to create a scheduler which runs at a particular day of week. For example my scheduler should run on every Monday at 11:50 PM. Please help me through the task.
PS: I went through these links How to schedule task daily + onStart() in Play 2.0.4? suggests using a cronJob expression to calculate next execution time. Is there a way to do using akka by default i.e. without a cronJob expression?
schedule(initialDelay: Duration, frequency: Duration, receiver: ActorRef, message: Any)
You just need to calculate the initialDelay on the scale (minutes, hours, days) that you want. In your case, you have to find out the time until the next Monday. That's not an issue related with Akka, just plain Java:
//In minutes
private long timeToNextMonday(){
Calendar now = Calendar.getInstance();
now.set(Calendar.HOUR, 23);
now.set(Calendar.MINUTE, 50);
int weekday = now.get(Calendar.DAY_OF_WEEK);
System.out.println(now.getTime());
if (weekday != Calendar.MONDAY){
// calculate how much to add
// the 2 is the difference between Saturday and Monday
int days = (Calendar.SATURDAY - weekday + 2) % 7;
now.add(Calendar.DAY_OF_YEAR, days);
}
Date date = now.getTime();
return (now.getTime().getTime() - System.currentTimeMillis())/(1000*60);
}
And then the schedule call itself is pretty straightforward:
Akka.system().scheduler().schedule(
Duration.create(timeToNextMonday, TimeUnit.MINUTES),
Duration.create(7, TimeUnit.DAYS),
actor, actorMessage,
Akka.system().dispatcher(), null);
public void onStart(Application application) {
try{
Duration.create(timeToNextMonday(), TimeUnit.MILLISECONDS),
Duration.create(7, TimeUnit.DAYS),
new Runnable() {
#Override
public void run() {
JPA.withTransaction(new F.Callback0() {
#Override
public void invoke() throws Throwable {
System.out.println("Printing time : " + new Date());
}
});
}
},
Akka.system().dispatcher());
}
catch (Throwable t){
HashMap<String,String> params = new HashMap<>();
Logger.error("{}:params:{}", "error while starting cron for Historical TW questions", params, t);
}
super.onStart(application);
}
//In minutes
private long timeToNextMonday(){
Calendar now = Calendar.getInstance();
while (now.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
now.add(Calendar.DATE, 1);
}
now.set(Calendar.HOUR,11);
now.set(Calendar.AM_PM,Calendar.PM);
now.set(Calendar.MINUTE,50);
now.set(Calendar.SECOND,00);
now.set(Calendar.MILLISECOND,00);
return now.getTime().getTime() - Calendar.getInstance().getTime().getTime();
}
I am making a ping program using Java sockets. One bug in my program is that sometimes it will not connect and will just sit there for ever. So I am trying to add a timeout (after twenty seconds) and the ping will fail. But I have no idea how to.
Here is part of my ping program:
boolean result = false;
long before1 = System.nanoTime();
out.println(new byte[64]);
System.out.println("(1) Sent 64 bytes of data to " + address
+ "...");
try {
if ((in.readLine()) != null) {
int size = in.readLine().toString().getBytes().length;
long after = System.nanoTime();
long s = ((after - before1) / 1000000L) / 1000;
System.out.println("(1) Recieved reply from " + address
+ " (" + size + " bytes), time = " + s
+ " seconds...");
result = true;
} else if ((in.readLine()) == null) {
long after = System.nanoTime();
long s = ((after - before1) / 1000000L) / 1000;
System.out.println("(1) Failed to recieve reply from "
+ address + ", time = " + s + " seconds...");
result = false;
}
} catch (IOException exc) {
long after = System.nanoTime();
long s = ((after - before1) / 1000000L) / 1000;
System.err.println("(1) Failed to recieve reply from "
+ address + ", time = " + s + " seconds...\nReason: "
+ exc);
result = false;
}
But I would like to measure time elapsed any where in my code, instead of:
long time = System.nanoTime();
If one part of my code is stuck doing something it will time out after 20 seconds.
Any suggestions on how to measure if twenty seconds has passed at the start of a try/catch block or anywhere else in my code so it doesn't get stuck during the ping?
As "jsn" and "jahory" said you need to do this with threads. Here's 2 useful links, you can check them ;)
How to implement timeout using threads
Adding a thread timeout to methods in Java
You can use Future and FutureTask:
ExecutorService pingExecutor = ... // executor service to run the ping in other thread
void showPing(final String target) throws InterruptedException {
Future<String> ping = executor.submit(new Callable<String>() {
public String call() {
String pingResult = ... // do your Ping stuff
return pingResult;
}});
System.out.println("Pinging..."); // do other things while searching
try {
System.out.println(future.get(20, TimeUnit.SECONDS)); // use future, waits 20 seconds for the task to complete
} catch (ExecutionException ex) {
} catch (TimeoutException tex) {
// Ping timed out
}
}
You can find some hints here: How do I call some blocking method with a timeout in Java?
Future interface looks like a good solution to your problem. Remember, however, that depending on what your task is doing, you probably would be not able to really cancel it. Additional info:
tutorial (see, in particular, Non-blocking algorithms section)
I'm currently reading in MIDI messages in real-time from my midi keyboard using a class that implements Receiver, and outputting the notes played.
The only information i receive when I press a note is the MidiMessage and a timeStamp.
I am trying to paint the notes as actual piano sheet music and currently the user has to set the bpm beforehand.
Therefore if I know the tempo is 120bpm (for example), how can I use the timeStamps to determine the length of the note pressed?
I'm assuming if I can convert the timeStamps into ticks (ppq), then I can use that to work out the timings.
Any help is greatly appreciated. Below is my "send" method in my Receiver class.
The 'firstStamp' and 'secondStamp' variables are just to output the length of a note. I took the timeStamp when a note was released and subtracted the timeStamp when it was pressed.
#Override
public void send(MidiMessage message, long timeStamp) {
String strMessage = null;
if (firstStamp == 0) {
firstStamp = timeStamp;
secondStamp = timeStamp;
}
firstStamp = secondStamp;
secondStamp = timeStamp;
stampDif = (secondStamp - firstStamp);
if (message instanceof ShortMessage) {
strMessage = decodeMessage((ShortMessage) message, timeStamp);
} else if (message instanceof MetaMessage) {
strMessage = decodeMessage((MetaMessage) message);
} else if (message instanceof SysexMessage) {
strMessage = decodeMessage((SysexMessage) message);
} else {
strMessage = "other message" + message.getStatus();
}
r_out.println("Timestamp: " + timeStamp + " " + strMessage);
r_printStream.println("Timestamp: " + timeStamp + " " + strMessage);
}
If the timestamp is in milliseconds then you can convert it to ticks like this:
long ticks = timestamp * bpm / (1000 * 60);
Bit you will get a high start tick since the timestamp is probably since Jan 1 1970. So if you want to have your first "tick" as 0 you need to keep track of if this is your first seen event.
if (tickOffset == -1) { // Using -1 as not initialized
tickOffset = ticks;
}
ticks = ticks - tickOffset;