我是Java的新手,我正在尝试生成一个将在特定时间运行的任务。有三种类型的时间表: a)在一年中每隔一天执行一次, b)在一个月内执行每个给定的次数(在特定月份中执行1到10次), c)执行每个月的每个星期(一个星期从1到5个星期)。
a到c的字母是日程安排的选择。
我尝试了几件事但到目前为止没有任何工作。我使用了TimerTask,Calendar和Timer API。我最近的努力如下:
public class Runner {
public static void runTask(int year, int month, int day, int hour, int minute, int second, String choice) {
Calendar startTime = Calendar.getInstance();
startTime.set(Calendar.YEAR, year );
startTime.set(Calendar.MONTH,month);
startTime.set(Calendar.DAY_OF_MONTH,day);
startTime.set(Calendar.HOUR_OF_DAY, hour);
startTime.set(Calendar.MINUTE, minute);
startTime.set(Calendar.SECOND, second);
startTime.set(Calendar.MILLISECOND, 0);
Calendar bStartTime = Calendar.getInstance();
bStartTime.set(Calendar.YEAR,year);
bStartTime.set(Calendar.MONTH,month-1);
bStartTime.set(Calendar.DAY_OF_MONTH,1);
bStartTime.set(Calendar.HOUR_OF_DAY,12);
bStartTime.set(Calendar.MINUTE, 0);
bStartTime.set(Calendar.SECOND, 0);
bStartTime.set(Calendar.MILLISECOND, 0);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy MMM dd");
long timeToEnd = 0;
if (choice.equals("a")) {
Timer time = new Timer();
time.schedule(new SpecificTask(), startTime.getTime(), TimeUnit.DAYS.toMillis(1));
}
else if(choice.equals("b")){
System.out.println("How many times the task should be done in "+year+"."+month);
int counter = 0;
Scanner sc = new Scanner(System.in);
counter = sc.nextInt();
Timer time = new Timer();
time.schedule(new SpecificTask(), bStartTime.getTime(), TimeUnit.DAYS.toMillis(30/counter));
System.out.println("Date of start : " + sdf.format(bStartTime.getTime()));
}
else if(choice.equals("c")){
Timer time = new Timer();
time.schedule(new SpecificTask(), startTime.getTime(), TimeUnit.SECONDS.toMillis(2));
}
else{
System.out.println("An error has been occured");
}
}
public static void main(String[] args) {
int year,month,day,hour,minute,second;
String choiceOfSchedule;
System.out.println("Welcome in The Ultimate Task Scheduler");
System.out.print("Select a type of schedule: ");
Scanner sc = new Scanner(System.in);
choiceOfSchedule = sc.nextLine();
System.out.println("Now set the task's starting time: ... ");
System.out.println(" Set year: ");
year = sc.nextInt();
System.out.print(" Set month: ");
month =sc.nextInt();
System.out.print(" Set day: ");
day = sc.nextInt();
System.out.print(" Set hour: ");
hour = sc.nextInt();
System.out.print( " Set minutes: ");
minute = sc.nextInt();
System.out.print(" Set seconds: ");
second = sc.nextInt();
runTask(year,month,day,hour,minute,second,choiceOfSchedule);