Java Timer Consumes CPU - java

//I call the methods under the init
{
showdate();
showtime();
}
void showdate()
{
Date d = new Date();
SimpleDateFormat a = new SimpleDateFormat("YYYY-MM-dd");
date.setText(a.format(d));
}
void showtime()
{
new Timer(0, new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
Date d = new Date();
SimpleDateFormat a = new SimpleDateFormat("hh:mm:ss");
time.setText(a.format(d));
}
}).start();
}
This code is consuming 80% of my CPU and I really need to show the time and date on my forms.

A delay time of 0 is unrealistic and will serve no purpose other than to burn CPU cycles. Try a more realistic value like 13 or 15, or even longer if it is OK with program function.

Related

doInBackground() stops and doesn't finish

I write a swing GUI application and I use a button. If I click on a button, my application needs to do some online request. I want to set a "Please wait" JPanel at this time. So I use the SwingWorker. It is all working. The doInBackground() method starts but it didn't finish.
I debugged the application and I see that if I create a new object, the application goes into a class FutureTask.java and call the method run(), after this it goes into ThreadPoolExecutor.java into the runWorker method and the thread stops there.
private void buttonBuchenActionPerformed(java.awt.event.ActionEvent evt) {
mainProg.showInfoWithoutButton(80000, "Please wait", mainProg.getPanel_first());
startPayment();
}
After a click on the button i change the Panel with the showInfoWithoutButton Methode. After the Panel is changed the startPayment() method starts.
public void startPayment() {
new SwingWorker<Void, Void>() {
#Override
public Void doInBackground() {
Calendar cal = Calendar.getInstance();
DateFormat formatDb = new SimpleDateFormat("yyyy-MM-dd");
Date date1;
try {
date1 = formatDb.parse(mainProg.getFreeRoom().getAbreiseBeds());
cal.setTime(date1);
cal.add(Calendar.DAY_OF_MONTH, -1);
} catch (ParseException ex) {
Logger.getLogger(EnterConfirmation.class.getName()).log(Level.SEVERE, null, ex);
}
String date = formatDb.format(cal.getTime());
try {
boolean paymentSuccess;
if(mainProg.getConfig().getString("terminal").equals("true")){
mainProg.getOpp().connectOpp();
paymentSuccess = mainProg.getOpp().startPayment(mainProg.getFreeRoom().getPriceGesamt(), mainProg);}
else paymentSuccess = true;
DBController db = new DBController();
db.initDBConnection();
//numberOfAvailbility is the unit.
String numberOfAvailbility = db.getQtyOfAvailbilityFromID(mainProg.getFreeRoom().getId());
if(paymentSuccess == true){
//----------------------------------
// HERE IT GOES TO FutureTask.java and the methode finish:
JsonNewBooking a = new JsonNewBooking(mainProg.getFreeRoom().getId(), 1, mainProg.getFreeRoom().getAnreiseBeds(), date, mainProg.getFreeRoom().getGuestnr(), mainProg.getBooking().getName(), mainProg.getBooking().getEmail(), mainProg.getBooking().getStreet(), mainProg.getBooking().getPlace(), mainProg.getBooking().getLand(), String.valueOf(mainProg.getFreeRoom().getPriceGesamt()));
//----------------------------------
String bookid = a.setBookingToBeds();
if(mainProg.getConfig().getString("terminal").equals("1"))
mainProg.getOpp().printReceipt(paymentSuccess);
if (!bookid.equals("null")) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
Date checkInDay = simpleDateFormat.parse(mainProg.getFreeRoom().getAnreiseBeds());
Date todayDate = simpleDateFormat.parse(simpleDateFormat.format(new Date()));
if (checkInDay.compareTo(todayDate) == 0) {
System.out.println(bookid);
//ReturnKeyWithoutTerminal because was 100% paid already
gui.return.returnWithoutTerminal(mainProg, bookid);
mainProg.getFreeRoom().reset();
mainProg.getBooking().reset();
mainProg.getPanel_bookNow().resetAll();
mainProg.resetPanel();
mainProg.getBackToMainPanelTimer().stop();
} else {
mainProg.getFreeRoom().reset();
mainProg.getFreeRoom().reset();
mainProg.getPanel_bookNow().resetAll();
mainProg.resetPanel();
mainProg.getBackToMainPanelTimer().stop();
}
} catch (ParseException ex) {
Logger.getLogger(EnterConfirmation.class.getName()).log(Level.SEVERE, null, ex);
}
}
}else
mainProg.getOpp().printReceipt(paymentSuccess);
} catch (IOException ex) {
Logger.getLogger(EnterConfirmation.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}}.execute();
}
Normally the method should finish normally but it stops at the line where I create the object "a" (sorry for the bad name).
Maybe someone have an idea why it calls the class FutureTask.java and the ThreadPoolExecutor.java and stops the doInBackground method.

how to call Java Threads in Web application

I need to create a thread, which everyday checks whether I have to create the tasks for this user or not. I know to create and run java threads by using main(). But how to run it in web application. Seriously I searched a lot and didn't get any answer for running in web application. I have few questions regarding this.
1 How my thread will initially start and from where it will run?
2 Do I need to define my thread in any XML file ?
This is my thread
public class TaskGenerationThread implements Runnable {
#Override
public void run(){
System.out.println("callled at "+ new Date());
/*try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}*/
/*List<Users> listOfCA = complianceUserService.getAllCA();
if(listOfCA !=null && !listOfCA.isEmpty()){
Users ca = complianceUserService.fetchUserByUserId(1).get(0);
Date currentDate = new Date();
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MONTH, 1);
calendar.set(Calendar.DATE, calendar.getActualMinimum(Calendar.DAY_OF_MONTH)); //getting first day of month
Date nextMonthFirstDay = calendar.getTime();
calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DAY_OF_MONTH)); //getting last day of month
Date nextMonthLastDay = calendar.getTime();
taskGeneratorService.generateCronJobTaskForCompanyCompliance(nextMonthFirstDay,nextMonthLastDay,ca);
}*/
}
}
I did this way. Implemented ServletContextListener and passed my Thread object. But didnt work
public class ThreadImplementation implements ServletContextListener{
ScheduledExecutorService listChecker =null;
#Override
public void contextInitialized(ServletContextEvent sce){
listChecker = Executors.newScheduledThreadPool(1);
listChecker.scheduleAtFixedRate(new TaskGenerationThread(), 01, 01, TimeUnit.SECONDS);
}
#Override
public void contextDestroyed(ServletContextEvent sce) {
if (listChecker != null) {
listChecker.shutdownNow();
try {
listChecker.awaitTermination(60, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Any help will be highly appreciated. Thank you
Write a class that
implements ServletContextListener
override
public void contextInitialized(ServletContextEvent sce)
and kick off some scheduler from here
e.g.
listChecker = Executors.newScheduledThreadPool(1);
listChecker.scheduleAtFixedRate(filechecker, 60, 60, TimeUnit.SECONDS);
note this works for Tomcat
Your contextDestroyed should be something like
#Override
public void contextDestroyed(ServletContextEvent sce) {
log.info("Scheduler entered contextDestroyed");
if (listChecker != null) {
listChecker.shutdownNow();
log.info("waiting [60 seconds] for collector threads to finsih");
try {
listChecker.awaitTermination(60, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
log.info("Scheduler finished contextDestroyed");
}
And of course you need to add it to web.xml
<listener>
<listener-class>
myPackage.Scheduler
</listener-class>
</listener>

How does joda datetimeformat impact the simpledateformat

As we know, simpleDateFormat are not thread-safe. When facing multi-thread, simpleDateFormat may throw some exceptions. So, I decided to use joda-time instead.
However, when I use joda-time together with simpleDateFormat, some thing strange happened.
Expect result:
simpleDateFormat throws exception, joda-time parsed successfully.
Actual result:
both parsed successfully.
Look at the code I wrote for test below.
public class MultiThreadDateTest {
private static SimpleDateFormat dformat = new SimpleDateFormat("yyyy-MM-dd");
private static DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MM-dd");
private static final int THREAD_SIZE = 4;
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < THREAD_SIZE; i++) {
new Thread(new JavaDateThread()).start();
new Thread(new JodaDateThread()).start();
}
}
private static class JavaDateThread implements Runnable {
#Override
public void run() {
try {
Date date = dformat.parse("1999-01-01");
System.out.println(Thread.currentThread().getId() + ": " + date);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
private static class JodaDateThread implements Runnable {
#Override
public void run() {
Date date = format.parseDateTime("2000-01-01").toDate();
System.out.println(Thread.currentThread().getId() + ": " + date);
}
}
}

Get current time only and update it in android

I need to get the current time only (without data) in HH:mm format (eg. 14:20) and then update it every second or minute. I kinda get it with this code, but is it possible to convert it to a string?
And I need to pass the value "time" in a separate public String.
Any solution?
Thanks
public class ClockCounter extends TimerTask {
public long time = System.currentTimeMillis();
#Override
public void run(){
time += 1000; //add 1 second to the time
//convert ms time to viewable time and set MainActivity.text (textview) text to this.
}
public long getTime(){ return time; }
}
UPDATE: Got it working with a service that runs every second.
Using liveData and coroutines:
val currentTime = liveData {
while (true){
emit(Calendar.getInstance().time)
kotlinx.coroutines.delay(1000)
}
}
You just need to have a final variable SimpleDateFormat.
final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
and you can get time with format in anywhere you want using this code:
String time = dateFormat.format(new Date());
you can do that like this :
private void clock() {
final Handler hander = new Handler();
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
hander.post(new Runnable() {
#Override
public void run() {
getTime();
clock();
}
});
}
}).start();
}
void getTime() {
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss", Local.getDefault());
textview.setText(dateFormat.format(new Date()));
}
You can use the code below for get curent Clock with Hours ,Minutes and Seconds
final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
String time = dateFormat.format(new Date());

Is there a cleaner way to write this polling loop?

I am writing automated test cases in Selenium/WebDriver in java. I have the following code implemented to poll for existing WebElements, but as I am not an expert in Java I was wondering if there is a cleaner way to write this method:
/** selects Business index type from add split button */
protected void selectBusinessLink() throws Exception
{
Calendar rightNow = Calendar.getInstance();
Calendar stopPolling = rightNow;
stopPolling.add(Calendar.SECOND, 30);
WebElement businessLink = null;
while (!Calendar.getInstance().after(stopPolling))
{
try
{
businessLink = findElementByLinkText("Business");
businessLink.click();
break;
}
catch (StaleElementReferenceException e)
{
Thread.sleep(100);
}
catch (NoSuchElementException e)
{
Thread.sleep(100);
}
catch (ElementNotVisibleException e)
{
Thread.sleep(100);
}
}
if (businessLink == null)
{
throw new SystemException("Could not find Business Link");
}
}
This particular line is what makes me think the code is a little dirty:
while (!Calendar.getInstance().after(stopPolling))
You can do something like this
long t = System.currentMillis(); // actual time in milliseconds from Jan 1st 1970.
while (t > System.currentMillis() - 30000 ) {
...
How about using the System time in millis?
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.SECOND, 30);
long stopPollingTime = calendar.getTimeInMillis();
while (System.currentTimeMillis() < stopPollingTime) {
System.out.println("Polling");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
}

Categories