当我们将音乐与评论信息爬下来之后,音乐的评论数就存在于我们的数据库中了。但是,音乐的评论数是每天都会变化的,我们需要每天重新爬一遍网易云音乐,更新音乐评论数。
但是,我们不可能每天都运行一次我们的爬虫程序,因此,我们需要一个定时任务,让程序在每天凌晨一点运行爬虫程序,更新评论数。接下来我们将使用Spring的定时任务完成这个功能。
在使用Spring定时任务之前,我们需要开启定时任务,在Spring Boot中,只需要在Application中添加@EnableScheduling标注即可:
@SpringBootApplication
@EnableScheduling
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
开启定时任务功能后,我们就能通过Spring的标注定制定时任务了:
@Component
public class ScheduledTask {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private Integer count0 = 1;
private Integer count1 = 1;
private Integer count2 = 1;
@Scheduled(fixedRate = 5000)
public void reportCurrentTime() throws InterruptedException {
System.out.println(String.format("---第%s次执行,当前时间为:%s", count0++, dateFormat.format(new Date())));
}
@Scheduled(fixedDelay = 5000)
public void reportCurrentTimeAfterSleep() throws InterruptedException {
System.out.println(String.format("===第%s次执行,当前时间为:%s", count1++, dateFormat.format(new Date())));
}
@Scheduled(cron = "0 0 1 * * *")
public void reportCurrentTimeCron() throws InterruptedException {
System.out.println(String.format("+++第%s次执行,当前时间为:%s", count2++, dateFormat.format(new Date())));
}
}
可以看到,我们在我们真正需要执行的方法上添加了@Scheduled
标注,表示这个方法是需要定时执行的。
在@Scheduled
标注中,我们使用了三种方式来实现了同一个功能:每隔5秒钟记录一次当前的时间:
fixedRate = 5000
表示每隔5000ms,Spring scheduling会调用一次该方法,不论该方法的执行时间是多少fixedDelay = 5000
表示当方法执行完毕5000ms后,Spring scheduling会再次调用该方法cron = "*/5 * * * * * *"
提供了一种通用的定时任务表达式,这里表示每隔5秒执行一次,更加详细的信息可以参考cron表达式。现在,让我们使用定时任务来更新歌曲评论数。由于在WebPage
表中已经存在所有歌曲的网页信息,我们只需要找到所有PageType为song的WebPage
,将其status设置为Status.uncrawl,然后启动爬虫即可。
首先,让我们在WebPageRepository
中添加如下方法:
在UpdateSchedule
中更新音乐评论数:
登录发表评论 登录 注册