Search code examples
macoscocoadaemonagentlaunchd

Is it possible to programmatically create and configure an agent/daemon in launchd Cocoa/OSX?


Desired scenario is: Tasks are set to run every day at 2am, and user want to run the task every day at 6:00pm. He starts an application and change it.

I've successfully created an agent that runs a task every given calendar dates. But I need these dates to be configurable by the user at his will, using an application. Is it possible to, programmatically, create/start/update an agent/daemon to run under launchd? If yes, how can I do this?


Solution

  • Just figured out how to put thing working. I was trying to write the agent into the system/root, and haven't noted it.

    I just created the .plist file in the logged user agent folder, using the following code:

    // create the plist agent file
    NSMutableDictionary *plist = [[NSMutableDictionary alloc] init];
    
    // set values here...
    
    // saves the agent plist file
    NSString *userLaunchAgentsPath = [[NSString alloc] initWithFormat:@"%@%@%@", @"/Users/", NSUserName(), @"/Library/LaunchAgents/myagent.plist"];
    [plist writeToFile:userLaunchAgentsPath atomically:YES];