我在Spring MVC 4项目中使用Amazon Push Notifications。我已经使用CronTrigger每天早上8点向Android应用发送推送通知。我还使用了Timezone和CronTrigger,以便用户根据各自的时区获得通知。
这是我的 WebConfig.java:
@Configuration
@EnableScheduling
@EnableWebMvc
@ComponentScan(basePackages="com.project")
public class WebConfig implements SchedulingConfigurer
{
protected static final Logger slf4jLogger = Logger.getLogger(WebConfig.class.getName());
private static final String cronExpression = "0 8 * * * ?";
/*@Bean
public MobileNotifSchedulerBean schedulerbean()
{
return new MobileNotifSchedulerBean();
}*/
@Bean
public InternalResourceViewResolver getInternalResourceViewResolver()
{
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/jsp/");
resolver.setSuffix(".jsp");
resolver.setSuffix(".html");
resolver.setSuffix(".htm");
return resolver;
}
@Bean
CronTrigger cronTrigger()
{
//The code in FetchUserTimeZones.java fetches all the user timezones which are stored in DynamoDb. Eg timeZone = "Asia/Calcutta";
String timeZone = null;
HashSet<String> userTimeZonesfromDB = FetchUserTimeZones.fetchUserTimeZone();
for (String s : userTimeZonesfromDB)
{
timeZone = s;
slf4jLogger.info(s);
}
return new CronTrigger(cronExpression, TimeZone.getTimeZone(timeZone));
}
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar)
{
taskRegistrar.addCronTask(new CronTask(new MobileNotifSchedulerBean(), cronTrigger()));
}
@Bean(destroyMethod="shutdown")
public Executor taskExecutor()
{
return Executors.newScheduledThreadPool(1);
}
}
这是我的 MobileNotifSchedulerBean: 此代码从DynamoDb中获取随机问题,并在CronTrigger设置为time(8am)的帮助下,在每个GCM registrationID的推送通知中发送它们。我使用了来自http://docs.aws.amazon.com/sns/latest/dg/mobile-push-gcm.html的 snsmobilepush.zip 。
@EnableScheduling
public class MobileNotifSchedulerBean implements Runnable
{
protected static final Logger slf4jLogger = Logger.getLogger(MobileNotifSchedulerBean.class.getName());
public MobileNotifSchedulerBean()
{
run();
}
public void sendQuestionNotif()
{
try
{
HashSet<String> reg_ids = FetchRegistrationIDs.fetchItems();
for (String s : reg_ids)
{
String REGISTRATION_IDs = s;
slf4jLogger.info(s);
MobileSNSPushNotification.sendNotification(REGISTRATION_IDs);
}
}
catch (IOException e)
{
//e.printStackTrace();
slf4jLogger.error(e);
slf4jLogger.error(e.getMessage());
slf4jLogger.error(e.getStackTrace());
}
}
@Override
public void run()
{
sendQuestionNotif();
}
}
请在我出错的地方帮助我。唯一的问题是推送通知在错误的时间进行,并且还有多个通知,而不是每个用户每天只进行1次推送通知(上午8点)。 TIA。
更新: Cron Expression有一个更正。我纠正了。
private static final String cronExpression = "0 0 8 * * ?"; // For everyday 8 am.
但问题还没有解决
答案 0 :(得分:1)
您应该为每个用户创建单独的计划
// spring bean
class Task implements Runnable {
public Task(TaskScheduler scheduler, String cron) {
HashSet<String> userTimeZonesfromDB = FetchUserTimeZones.fetchUserTimeZone();
for (String tz : userTimeZonesfromDB) {
scheduler.schedule(this, new CronTrigger(cron, TimeZone.getTimeZone(tz)));
}
}
@Override
public void run() {
// notify
}
}