Separate Thread on GlassFish server

glassfish, jakarta-ee, java, service

Solution

@Schedule

If you are using Ejb 3.1 (glassfish 3.x), you may use the @Schedule annotation to have the container invoke a method in a specified interval or at a given calendar time. Allowing you to avoid handling threads in your own code

Read about ejb 3.1 timer

@Stateless
public class LabbBean {

    @EJB
    WorkerEjb workerEjb;

    @Schedule(second="*/5", minute="*",hour="*", persistent=false)
    public void myMethod() {
        for (all jobs found in db){
            workerEjb.workerMethod(job);    
        }
    }
}

@Stateless
public class WorkerEjb {
    @Asynchronous
    public void workerMethod(job) {
        //Send emails
    }
}

If you wanted to do the work in separate threads, the @Schedule annotated method could call a worker-ejb with the worker-method annotated as @Asynchronous

@Timeout

I just realised you wanted the schedule to be initiated from the database. An option the would be to initiate a bunch of timers programmatically using a @Singleton ejb with @Startup annotation. The timeout annotated method would be called in separate threads if some timers run out at the same time.

@Singleton
@Startup
public class LabbBean {
    @Resource
    protected TimerService timerService;

    @PostConstruct
    public void init() {
        //Init your timers from the data in the database here
        for (all your timers) {
            TimerConfig config = new TimerConfig();
            config.setInfo("timer1");
            config.setPersistent(false);

            ScheduleExpression schedule = new ScheduleExpression();
            schedule.dayOfMonth(10);
            schedule.minute(2);
            timerService.createCalendarTimer(schedule, config);
        }
    }

    //method called when timeout occurs
    @Timeout
    public void timeoutHandler(Timer timer) {
        String name = timer.getInfo().toString();
        System.out.println("Timer name=" + name);
    }
}

Problem

I'm doing my graduation project, and have run into a dilemma here. I need to make an application that generates PDFs and emails them to people on a schedule defined by data in the database. I'm working for a company with this project, and we already have a GlassFish application server that we use. It would be best if the entire solution is delivered in one package, as it is now. Client with webstart Web Application etc. is all in one package My new service needs to run on a separate thread, generate reports and send them out on emails. From what I can read on the web, running your own threads in an application server as GlassFish is highly discouraged, so it sounds like I need to make my own separate application. Can this really be? What are your comments, and what are the best practices for this?

Original source