Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java EE 6 @Startup and @Schedule never being executed

I have the following singleton which should be executed when the web application starts but it does not, and the scheduled task does not run either.

@Singleton
@Startup
public class Scheduler {

    private static int count = 0;

    @PostConstruct
    public void onStartup() {
        System.out.println("Initialization success.");
    }

   @Schedule(second="*/10", minute="*", hour="*")
   public void execute() {
      System.out.println("its running count..."+count);
      count++;
   }
}

I am using Glassfish server 3.1.2.

EDIT

The startup method is now being executed but the schedule method does not run.

like image 813
Paul Blundell Avatar asked Mar 20 '13 10:03

Paul Blundell


4 Answers

My problem was that I used the wrong Singleton class, not javax.inject.Singleton but javax.ejb.Singleton

like image 68
Jojo Avatar answered Nov 18 '22 11:11

Jojo


Adding another answer as there was some questions on Boreded's own answer.

The reason why setting persistence=false solved the problem is likely due to that persistent timers are not re-created if already existing when keepstate is set to true.

you should see the following in the log

INFO: keepstate is true and will not create new auto timers during deployment.

I think my answer here (together with Roland Tiefenbrunner's answer on same question) covers the issue somewhat well.

like image 32
Aksel Willgert Avatar answered Nov 18 '22 12:11

Aksel Willgert


Also watch out for the default values of the annotation. Hour, minute and second default to 0 NOT *, whereas the others default to * , so e.g. @Schedule(minute = "*/20", persistent = false) will only fire at 20 + 40 mins past midnight.

@Target(value=METHOD)
@Retention(value=RUNTIME)
public @interface Schedule {
   String dayOfMonth() default "*";

   String dayOfWeek() default "*";

   String hour() default "0";

   String info() default "";

   String minute() default "0";

   String month() default "*";

   boolean persistent() default true;

   String second() default "0";

   String timezone() default "";

   String year() default "*";
}
like image 21
Jon Vaughan Avatar answered Nov 18 '22 12:11

Jon Vaughan


For anyone else with a similar issue adding the following fixed my problem:

persistent=false

So my schedule annotation is now

@Schedule(second="*/10", minute="*", hour="*", persistent=false)
like image 1
Paul Blundell Avatar answered Nov 18 '22 11:11

Paul Blundell