如何在特定日期执行方法?

时间:2015-07-08 17:20:03

标签: objective-c macos cocoa badge

我的Mac应用程序会在特定时间更新它的徽章编号 这是我的功能:

- (void)setBadgeNumber
{
    // Sets the badge number to 1.
    [[[NSApplication sharedApplication] dockTile] setBadgeLabel:@"1"];

    // Sends a notification.
    NSUserNotificationCenter *nc = [NSUserNotificationCenter defaultUserNotificationCenter];
    NSUserNotification *notification = [[NSUserNotification alloc] init];
    notification.title = @"Update";
    notification.informativeText = @"There's something new in the app!";
    [nc deliverNotification:notification];
}

我想知道你是否可以在某个特定日期执行此功能(例如:08-08-2015) 即使应用程序没有运行(也就是应用程序正在运行) 有人知道你是否可以在某个日期(和时间)执行某个方法吗?

4 个答案:

答案 0 :(得分:1)

根据您所追求的目标,您有很多选择。

明显的起点是NSTimer。

还有performSelector withDelay函数系列。

最后,我有时会使用一个很酷的扩展,延迟阻止。

哦,还有一个 - 您还可以设置本地通知。

我更喜欢NSTimer' ID_ commands 0x8000 through 0xDFFF

<强>更新

<强>的NSTimer:

initWithFireDate:interval:target:selector:userInfo:repeats:

<强> dispatch_after

NSTimer *saveProgressSizeTimer = [[NSTimer alloc]
    initWithFireDate:[NSDate dateWithTimeIntervalSinceNow:2.0f]
    interval:1.0f
    target:self
    selector:@selector(myMethod:)
    userInfo:myUserInfo
    repeats:YES];  // This Will Be Executed After 2 Seconds

答案 1 :(得分:1)

Launchd通常与Launch Agents和Launch Daemons相关联,但Apple也建议将其作为Unix cron功能的替代品。

使用此功能,您可create a launchd property listschedule jobs to run periodically或指定的日历间隔。

如果您需要程序运行代码,请使用在应用程序调用时调用相应函数的参数,然后退出。然后,使用launchd通过配置属性列表并将其添加到正确的文件夹(例如 / Library / LaunchAgents

,在指定的日期和时间使用该参数调用您的程序。

答案 2 :(得分:1)

声明一个NSTimer属性并调用您的方法来检查是否相同。

 self.nstimer=  [NSTimer scheduledTimerWithTimeInterval:0.10 target:self selector:@selector(updateTime:) userInfo:nil repeats:YES];

这将是您的更新方法:

- (int)updateTime:(NSTimer *)timer
 {

NSString *Time1 = @"2016-02-20 03:19:05 +0000";
NSString *Time2 = @"2016-02-20 03:19:05 +0000";
NSDateFormatter *dateFormatter=[NSDateFormatter new];
[dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss Z"];

NSDate *tokonExpireDate1=[dateFormatter dateFromString:Time1];
NSDate *tokonExpireDate2=[dateFormatter dateFromString:Time2];


if ([tokonExpireDate1 compare:tokonExpireDate2] == NSOrderedDescending) {
    //"date1 is later than date2
    NSLog(@"Later Date");

} else if ([tokonExpireDate1 compare:tokonExpireDate2] == NSOrderedAscending) {
    //date1 is earlier than date2
    NSLog(@"Previous Date");

} else {
    //dates are the same

    NSLog(@"Same Date"); 
    //CALL your method here.
}
}

我把这个方法调用了0.10秒。如果您需要按天间隔(2天,3天后等)拨打电话,请将您的日期转换为秒,然后致电。希望你知道这一点。它会工作。谢谢。

答案 3 :(得分:0)

要在特定时间执行方法,请查看NSTimer。但是,当应用程序当前未运行时,我不知道如何执行应用程序的方法。据我所知,只有退出方式在特定时间(使用给定参数)启动应用程序或使用背景资料,例如NSDockTilePlugin。

相关问题