首先,我们先看一下微信运动排行榜的页面以及大致的工作原理。
微信排行榜的每天定时刷新就是定时任务最常用的场景,像我们的微信运动每天晚上大约都是在10点多定时刷新数据。
下面,我将写一个模仿这样的定时任务的例子。
目录结构
在Config包下新建QuartzConfig,SporterJob,SportJobFactory类
- QuartzConfig类
public class QuartzConfig {
@Autowired
private SpringJobFactory springJobFactory;
@Bean
public SchedulerFactoryBean schedulerFactoryBean(){
SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
schedulerFactoryBean.setJobFactory(springJobFactory);
return schedulerFactoryBean;
}
@Bean
public Scheduler scheduler() {
return schedulerFactoryBean().getScheduler();
}
}
- SporterJob类
@Component
public class SporterJob {
@Resource
private UpdateService updateService;
@Scheduled(cron = "0 26 22 * * ?")
public void updateTodayWalks() throws Exception {
updateService.updateWalks();
}
}
corn里设置刷新时间,corn的用法见我之前的文章。
- SporterJobFactory类
@Component
public class SpringJobFactory extends AdaptableJobFactory {
@Autowired
private AutowireCapableBeanFactory capableBeanFactory;
@Override
protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
Object jobInstance = super.createJobInstance(bundle);
capableBeanFactory.autowireBean(jobInstance);
return jobInstance;
}
}
实体类
- 运动者(Walker)
@Entity
@Data
public class Walker implements Serializable {
@Id
@GeneratedValue
private Integer id;
private String account;
private String password;
private String nickname;
private String avatar;
@OneToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
@JoinColumn(name = "account",referencedColumnName = "account")
private List sportDataList;
public Walker(String account, String password, String nickname, String avatar, List sportDataList) {
this.account = account;
this.password = password;
this.nickname = nickname;
this.avatar = avatar;
this.sportDataList = sportDataList;
}
}
- 运动数据(SportData)
@Entity
@Data
public class SportData implements Serializable {
@Id
@GeneratedValue
private Integer id;
private Integer steps;
private String evaluate;
private Date date;
public SportData(Integer steps, String evaluate, Date date) {
this.steps = steps;
this.evaluate = evaluate;
this.date = date;
}
}
- UpdateService类
public interface UpdateService {
void updateWalks();
}
- SportDataRepositry接口
public interface SportDataRepositry extends JpaRepository {
}
- 实现类(UpdateServiceImpl)
@Service
public class UpdateServiceImpl implements UpdateService {
@Resource
private SportDataRepositry sportDataRepositry;
@Override
public void updateWalks() {
List list = sportDataRepositry.findAll();
Random random = new Random();
for (int i=0;i
页面代码
- 登录界面
Title
- 运动数据界面
SporterList