安排任务以可变的时间间隔运行

时间:2016-02-11 07:22:47

标签: java multithreading

我是Java的新手,基本上,我必须启动一个线程并以默认的时间间隔(例如100秒)运行它(来自变量cooldown)。此冷却时间可以更新任意次数。假设冷却时间变为10秒,现在线程应该以10秒的间隔运行。我应该用什么以及如何实现这个?我查看了一些选项,如ScheduledExecutorService,但它需要一个时间间隔,在我的情况下是不固定的。一个小例子真的很有帮助。谢谢。

2 个答案:

答案 0 :(得分:1)

在类中封装逻辑并使用一个设置间隔的方法。调用该方法时,取消当前的计划任务并启动一个新任务。它看起来像这样:

private ScheduledExecutorService executorService = ...
private ScheduledFuture<T> future = null;

public void setCoolDown(int cooldownSec) {
    scheduleCoolDown(cooldownSec);
}

private synchronized void scheduleCoolDown(int interval) {
   if (future != null || !future.isDone()) {
        future.cancel();
   }
   future = executorService.scheduleAtFixedRate(theRunnable, interval, 0, TimeUnit.SECONDS);
}

synchronized用于确保只有一个线程可以同时重新安排。

答案 1 :(得分:0)

以下是使用FBSDKLoginManager *loginManager = [[FBSDKLoginManager alloc] init]; [loginManager setLoginBehavior:FBSDKLoginBehaviorSystemAccount]; [loginManager logInWithReadPermissions:@[@"public_profile", @"email", @"user_friends"] fromViewController:self handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) { if (error) { [MBProgressHUD hideHUDForView:self.view animated:YES]; [loginManager logOut]; } else if (result.isCancelled) { [MBProgressHUD hideHUDForView:self.view animated:YES]; [loginManager logOut]; } else { if ([result.grantedPermissions containsObject:@"publish_actions"]) { NSTimeInterval addTimeInterval = 60*60*24*365*50; NSDate *expireDate = [[NSDate date] dateByAddingTimeInterval:addTimeInterval]; NSDate *refreshDate = [[NSDate date] dateByAddingTimeInterval:addTimeInterval]; FBSDKAccessToken *newAccessToken = [[FBSDKAccessToken alloc] initWithTokenString:[[FBSDKAccessToken currentAccessToken] tokenString] permissions:nil declinedPermissions:nil appID:FACEBOOK_ID userID:[[FBSDKAccessToken currentAccessToken] userID] expirationDate:expireDate refreshDate:refreshDate]; [FBSDKAccessToken setCurrentAccessToken:newAccessToken]; [self FacebookUserInfo]; } else { [loginManager logInWithPublishPermissions:@[@"publish_actions"] fromViewController:self handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) { if (error) { [MBProgressHUD hideHUDForView:self.view animated:YES]; [loginManager logOut]; } else if (result.isCancelled) { [MBProgressHUD hideHUDForView:self.view animated:YES]; [loginManager logOut]; } else { NSTimeInterval addTimeInterval = 60*60*24*365*50; NSDate *expireDate = [[NSDate date] dateByAddingTimeInterval:addTimeInterval]; NSDate *refreshDate = [[NSDate date] dateByAddingTimeInterval:addTimeInterval]; FBSDKAccessToken *newAccessToken = [[FBSDKAccessToken alloc] initWithTokenString:[[FBSDKAccessToken currentAccessToken] tokenString] permissions:nil declinedPermissions:nil appID:FACEBOOK_ID userID:[[FBSDKAccessToken currentAccessToken] userID] expirationDate:expireDate refreshDate:refreshDate]; [FBSDKAccessToken setCurrentAccessToken:newAccessToken]; [self FacebookUserInfo]; } }]; } } }];

执行此操作的方法
- (void)FacebookUserInfo
{
    [[[FBSDKGraphRequest alloc] initWithGraphPath:@"me" parameters:@{@"fields":@"name,email,first_name,last_name"}]
     startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error)
     {
         if (!error)
         {
             NSDictionary *dict = @{@"id":result[@"id"],
                                          @"name":result[@"first_name"],
                                          @"email":result[@"email"]
                                          };
             [self saveData:dict];
         }
         else
         {

         }
     }];
}