Programar uma tarefa para horário especifico

10 respostas Resolvido
Jpsdcq

Boa tarde galera!
Gostaria de enviar um e-mail (Isso já esta programado) todos os dias vamos supor as 10:00am.
Alguém sabe alguma API ou algum método que resolva meu problema?
Obrigado!

PS: Estou usando Swing

10 Respostas

guivirtuoso

Acho que isso pode te ajudar:

http://stackoverflow.com/questions/7814089/how-to-schedule-a-periodic-task-in-java

Jpsdcq

Obrigado vou dar uma olhada!

guivirtuoso

Acabei não mencionando, porque hoje já temos recursos na API do java, mas tem uma lib um pouco mais antiga mas muito popular chamada Quartz.

https://quartz-scheduler.org/

Pode ser útil tbm.

Jpsdcq

Acho que o método Cron faz exatamente o que eu quero, porém é muito complicado você tem alguma experiencia com essa API?

guivirtuoso

Tais falando do Quartz?

Tenho alguma… mas na internet tem muito material … muito mesmo.

Da uma pesquisa… tente implementar algo… e ai poste as duvidas.

:wink:

Jpsdcq

Bom eu tentei implementar aqui, porém está dando erro, pra teste só queria exibir um Print na tela de 10 em 10 segundos. (Na versão final gostaria de definir um horario especifico e diario). Mas pra começar a entender vou fazer de 10 em 10 seg.

package controle;

import javax.swing.JFrame;
import javax.swing.JPanel;

import org.quartz.CronScheduleBuilder;
import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;

public class teste extends JFrame {

	private JPanel contentPane;

	/**
	 * Launch the application.
	 */
		
		public static void main(String[] args) {
			SchedulerFactory shedFact = new StdSchedulerFactory();
			try {
				Scheduler scheduler = shedFact.getScheduler();
				scheduler.start();
				JobDetail job = JobBuilder.newJob(MyJob.class)
						.withIdentity("MyJob", "grupo01").build();
				Trigger trigger = TriggerBuilder
						.newTrigger()
						.withIdentity("MyJob", "grupo01")
						.withSchedule(
								CronScheduleBuilder
										.cronSchedule("0/5 * * * * ?")).build();
				scheduler.scheduleJob(job, trigger);
			} catch (SchedulerException e) { // TODO Auto-generated catch block
												// e.printStackTrace(); } } }
			}
		}
	
		public class MyJob implements Job {
	    @Override
	    public void execute(JobExecutionContext context) throws JobExecutionException {
	       System.out.println("Servico executado conforme agendamento");
	    }
	} 
}

Ai esta estourando uma Exception:

SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/Z:/SISTEMAS/Jars/slf4j-log4j12-1.5.8.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/Z:/SISTEMAS/jar%20quartz/slf4j-log4j12-1.7.7.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
16/01/07 16:05:22 INFO impl.StdSchedulerFactory: Using default implementation for ThreadExecutor
16/01/07 16:05:22 INFO simpl.SimpleThreadPool: Job execution threads will use class loader of thread: main
16/01/07 16:05:22 INFO core.SchedulerSignalerImpl: Initialized Scheduler Signaller of type: class org.quartz.core.SchedulerSignalerImpl
16/01/07 16:05:22 INFO core.QuartzScheduler: Quartz Scheduler v.2.2.2 created.
16/01/07 16:05:22 INFO simpl.RAMJobStore: RAMJobStore initialized.
16/01/07 16:05:22 INFO core.QuartzScheduler: Scheduler meta-data: Quartz Scheduler (v2.2.2) 'DefaultQuartzScheduler' with instanceId 'NON_CLUSTERED'
  Scheduler class: 'org.quartz.core.QuartzScheduler' - running locally.
  NOT STARTED.
  Currently in standby mode.
  Number of jobs executed: 0
  Using thread pool 'org.quartz.simpl.SimpleThreadPool' - with 10 threads.
  Using job-store 'org.quartz.simpl.RAMJobStore' - which does not support persistence. and is not clustered.

16/01/07 16:05:22 INFO impl.StdSchedulerFactory: Quartz scheduler 'DefaultQuartzScheduler' initialized from default resource file in Quartz package: 'quartz.properties'
16/01/07 16:05:22 INFO impl.StdSchedulerFactory: Quartz scheduler version: 2.2.2
16/01/07 16:05:22 INFO core.QuartzScheduler: Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED started.
16/01/07 16:05:25 ERROR core.ErrorLogger: An error occured instantiating job to be executed. job= 'grupo01.MyJob'
org.quartz.SchedulerException: Problem instantiating class 'controle.teste$MyJob' [See nested exception: java.lang.InstantiationException: controle.teste$MyJob]
	at org.quartz.simpl.SimpleJobFactory.newJob(SimpleJobFactory.java:58)
	at org.quartz.simpl.PropertySettingJobFactory.newJob(PropertySettingJobFactory.java:69)
	at org.quartz.core.JobRunShell.initialize(JobRunShell.java:127)
	at org.quartz.core.QuartzSchedulerThread.run(QuartzSchedulerThread.java:375)
Caused by: java.lang.InstantiationException: controle.teste$MyJob
	at java.lang.Class.newInstance(Unknown Source)
	at org.quartz.simpl.SimpleJobFactory.newJob(SimpleJobFactory.java:56)
	... 3 more
Caused by: java.lang.NoSuchMethodException: controle.teste$MyJob.<init>()
	at java.lang.Class.getConstructor0(Unknown Source)
	... 5 more
16/01/07 16:05:25 INFO simpl.RAMJobStore: All triggers of Job grupo01.MyJob set to ERROR state.
guivirtuoso

Duas coisas…

Primeiro, atendendo à convenção, nome de Classe é Sempre Maiúsculo.

então renomeie sua classe para Teste … :wink:

Segundo, sugiro que você crie um arquivo separado para a classe MyJob.

Qualquer coisa da mais uma lida nesse material:

http://blog.caelum.com.br/agendamento-de-tarefas-em-aplicacoes-web-um-truque-com-quartz/

Abs

Jpsdcq

Bom primeiro passo concluido, separei o MyJob em outra Classe e deixei o codigo assim:

public class teste extends JFrame {

	private JPanel contentPane;

	/**
	 * Launch the application.
	 */
		
		public static void main(String[] args) {
			
			
			try {
				SchedulerFactory shedFact = new StdSchedulerFactory();
				Scheduler scheduler = shedFact.getScheduler();
				
				
				scheduler.start();
				JobDetail job = JobBuilder.newJob(MyJob.class).withIdentity("MyJob", "grupo01").build();
				Trigger trigger = TriggerBuilder.newTrigger().withIdentity("MyJob", "grupo01").withSchedule(CronScheduleBuilder.cronSchedule("0/1 * * * * ?")).build();
				scheduler.scheduleJob(job, trigger);
			} catch (SchedulerException e) {
			 e.printStackTrace(); 
			 
			}
		}
	
}

Assim funcionou de boa cada 1 segundo ele printava na tela.

Agora estou na Duvida de como seria para definir um horario diario para executar o Job?
Como ficaria esse trecho ?

Trigger trigger = TriggerBuilder.newTrigger().withIdentity("MyJob", "grupo01").withSchedule(CronScheduleBuilder.cronSchedule("0/1 * * * * ?")).build();

Li sobre os 7 parametros o (Segundos, Minutos, Hora , Dia do Mes, Mês, Dia da Semana, Ano)
Porem se eu deixar (0,0,15 ,* , * ,* , ?) dá erro diz que é invalido.

Jpsdcq
Solucao aceita

Consegui !!!
Muito Obrigado guivirtuoso

Funcionou !

Trigger trigger = TriggerBuilder.newTrigger().withIdentity("MyJob", "grupo01").withSchedule(CronScheduleBuilder.cronSchedule("0 55 16 * * ?")).build();

Para quem futuramente tiver esta duvida este post ajudou bastante também!

guivirtuoso

Não deixe de estudar sobre Cron … é um padrão de agendamento… .muito usado no Linux inclusive p/ registrar as Crons …

Aceita várias configurações, de diversas formas…

:wink:

Criado 7 de janeiro de 2016
Ultima resposta 7 de jan. de 2016
Respostas 10
Participantes 2