添加任务类

清理用户需要清理2个表,新建类net.wendal.nutzbook.quartz.job.CleanNonActiveUserJob

  1. package net.wendal.nutzbook.quartz.job;
  2. import java.util.Date;
  3. import net.wendal.nutzbook.bean.User;
  4. import net.wendal.nutzbook.bean.UserProfile;
  5. import org.nutz.dao.Cnd;
  6. import org.nutz.dao.Dao;
  7. import org.nutz.dao.Sqls;
  8. import org.nutz.dao.sql.Sql;
  9. import org.nutz.ioc.loader.annotation.Inject;
  10. import org.nutz.ioc.loader.annotation.IocBean;
  11. import org.nutz.log.Log;
  12. import org.nutz.log.Logs;
  13. import org.quartz.Job;
  14. import org.quartz.JobExecutionContext;
  15. import org.quartz.JobExecutionException;
  16. @IocBean
  17. public class CleanNonActiveUserJob implements Job {
  18. private static final Log log = Logs.get();
  19. @Inject protected Dao dao;
  20. public void execute(JobExecutionContext context) throws JobExecutionException {
  21. log.debug("clean Non-Active User , start");
  22. Date deadtime = new Date(System.currentTimeMillis() - 24*60*60*1000L); // 一天, 测试的时候可以改成1小时之类的
  23. Cnd cnd = Cnd.where("userId", ">", 10).and("createTime", "<", deadtime).and(Cnd.exps("emailChecked", "=", false).or("email", "IS", null));
  24. int deleted = dao.clear(UserProfile.class, cnd);
  25. log.debugf("delete %d UserProfile", deleted);
  26. Sql sql = Sqls.create("delete from $user_table where id > 10 and not exists (select 1 from $user_profile_table where $user_table.id = uid ) and ct < @deadtime");
  27. sql.vars().set("user_table", dao.getEntity(User.class).getTableName());
  28. sql.vars().set("user_profile_table", dao.getEntity(UserProfile.class).getTableName());
  29. sql.params().set("deadtime", deadtime);
  30. dao.execute(sql);
  31. log.debugf("delete %d User", sql.getUpdateCount());
  32. log.debug("clean Non-Active User , Done");
  33. }
  34. }

关键点

  • 先清除id>10且创建时间大于1天的邮箱未激活或者没填邮箱的用户, 请注意Cnd.exps的用法,构建多条件语句必备
  • 第二段是自定义sql,这里用到参数(转为?号),也用到变量(直接替入)
  • 这里并没有太明显的会抛出异常的情况,所以不必加上事务了.
  • 良好的日志是基本素养哦
  • 是java.util.Date啊啊啊啊