1

I want to call a method on every 5th second, I used a timer, but I don't know how to use it properly.

I have a method in one CountryDTO class as below.

public MoviesDTO getMovieDTOByName(String movieName) {
        Session session = factory.openSession();
        String hql = "FROM MoviesDTO WHERE name=:nm";
        Query query = session.createQuery(hql);
        query.setParameter("nm", movieName);
        return (MoviesDTO) query.uniqueResult();
    }

And I call it from the main method.as below:

public static void main(String[] args) {
        Timer timer = new Timer();
        CountryDAO countryDAO = new CountryDAO();

        timer.schedule(countryDAO.getMovieDTOByName("Rabgo"), 5000);

    }

But, I'm getting this below exception:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    The method schedule(TimerTask, long) in the type Timer is not applicable for the arguments (MoviesDTO, int)
Elydasian
  • 2,016
  • 5
  • 23
  • 41

3 Answers3

1

Using Timer is not a good idea.Using ScheduledThreadPoolExecutor instead if you use jdk 1.5 or later.
doc: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledThreadPoolExecutor.html

reason:

Java Timer vs ExecutorService?

Community
  • 1
  • 1
fairjm
  • 1,115
  • 12
  • 26
0

You have a compilation error as the log says. The method schedule takes 2 arguments (TimerTask, long) instead of (MoviesDTO, int) that you have provided.

Take a look at How to set a timer in Java (mentioned by Masked Man in the comment on your post) to get the solution

Community
  • 1
  • 1
jMounir
  • 495
  • 2
  • 11
0

There are plenty third party jar(s) like Quartz scheduler available for java. This kind of jar(s) internally handle all the required scheduling process for us and we can focus on our business logic of scheduler.

Quartz is basically made for handling complex schedule in the Java. You must have knowledge of cronjob in this case.

You can also refer CronMaker.

(Note:- This is just suggestion for you. If your scheduling process is taking to-much time to handle it and you are diverting from your use-case then you can go further with this suggestion.)

Dhiral Kaniya
  • 1,941
  • 1
  • 19
  • 32