macos 如何将任务设置为每隔一段时间运行一次?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/132955/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:55:31  来源:igfitidea点击:

How do I set a task to run every so often?

macosshelltimecronscheduled-tasks

提问by stalepretzel

How do I have a script run every, say 30 minutes? I assume there are different ways for different OSs. I'm using OS X.

我如何让脚本每隔 30 分钟运行一次?我假设不同的操作系统有不同的方法。我正在使用 OS X。

回答by Mecki

Just use launchd. It is a very powerful launcher system and meanwhile it is the standard launcher system for Mac OS X (current OS X version wouldn't even boot without it). For those who are not familiar with launchd(or with OS X in general), it is like a crossbreed between init, cron, at, SysVinit (init.d), inetd, upstartand systemd. Borrowing concepts of all these projects, yet also offering things you may not find elsewhere.

只需使用launchd。它是一个非常强大的启动器系统,同时它也是 Mac OS X 的标准启动器系统(没有它,当前的 OS X 版本甚至无法启动)。对于那些不熟悉launchd(或一般来说不熟悉OS X)的人来说,它就像是initcronat、 SysVinit ( init.d) inetdupstart和之间的杂交品种systemd。借用所有这些项目的概念,同时也提供您在其他地方可能找不到的东西。

Every service/task is a file. The location of the file depends on the questions: "When is this service supposed to run?" and "Which privileges will the service need?"

每个服务/任务都是一个文件。文件的位置取决于以下问题:“该服务应该何时运行?” 和“服务需要哪些特权?”

System tasks go to

系统任务转到

/Library/LaunchDaemons/

if they shall run, no matter if any user is logged in to the system or not. They will be started with "root" privileges.

如果它们应该运行,无论是否有用户登录到系统。它们将以“root”权限启动。

If they shall only run if anyuser is logged in, they go to

如果他们只在任何用户登录时运行,他们就会去

/Library/LaunchAgents/

and will be executed with the privileges of the user that just logged in.

并且将以刚刚登录的用户的权限执行。

If they shall run only if youare logged in, they go to

如果它们仅在登录时运行,它们将转到

~/Library/LaunchAgents/

where ~ is your HOME directory. These task will run with your privileges, just as if you had started them yourself by command line or by double clicking a file in Finder.

其中 ~ 是您的 HOME 目录。这些任务将以您的权限运行,就像您通过命令行或双击 Finder 中的文件自己启动它们一样。

Note that there also exists /System/Library/LaunchDaemonsand /System/Library/LaunchAgents, but as usual, everything under /Systemis managed by OS X. You shall not place any files there, you shall not change any files there, unless you really know what you are doing. Messing around in the Systems folder can make your system unusable (get it into a state where it will even refuse to boot up again). These are the directories where Apple places the launchdtasks that get your system up and running during boot, automatically start services as required, perform system maintenance tasks, and so on.

请注意,也存在/System/Library/LaunchDaemonsand /System/Library/LaunchAgents,但像往常一样,下面的所有内容/System都由 OS X 管理。您不得在那里放置任何文件,也不得在那里更改任何文件,除非您真的知道自己在做什么。在 Systems 文件夹中乱搞可能会使您的系统无法使用(使其进入甚至拒绝再次启动的状态)。这些是 Apple 放置launchd在引导期间启动和运行系统、根据需要自动启动服务、执行系统维护任务等任务的目录。

Every launchdtask there is a file in plist format. It should have reverse domain name notation. E.g. you can name your task

每个launchd任务都有一个 plist 格式的文件。它应该有反向域名符号。例如,您可以命名您的任务

com.example.my-fancy-task.plist

This plist can have various options and settings. Writing one per hand is suboptimal, you may want to get the free tool Lingonto create your tasks. This tool used to be free, now it costs $5 in the app store and $10 as the non app store version (the non app store version is much more powerful and if you already plan on paying for it, seriously, get the non app store version). If anyone knows a comparable tool that is freeware or open source, drop me a line in the comments and I will rather recommend that one (don't want to advertise here for commercial software).

这个 plist 可以有各种选项和设置。一只手写一个是次优的,您可能想要获得免费工具Lingon来创建您的任务。这个工具曾经是免费的,现在在应用商店需要 5 美元,非应用商店版本需要 10 美元(非应用商店版本功能更强大,如果您已经计划付费,请认真地获取非应用商店版本)版本)。如果有人知道免费软件或开源软件的类似工具,请在评论中给我留言,我宁愿推荐那个(不想在这里为商业软件做广告)。

Just as an example, it could look like this

举个例子,它可能看起来像这样

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.example.my-fancy-task</string>
    <key>OnDemand</key>
    <true/>
    <key>ProgramArguments</key>
    <array>
        <string>/bin/sh</string>
        <string>/usr/local/bin/my-script.sh</string>
    </array>
    <key>StartInterval</key>
    <integer>1800</integer>
</dict>
</plist>

This agent will run the shell script /usr/local/bin/my-script.sh every 1800 seconds (every 30 minutes). You can also have task run on certain dates/times (basically launchd can do everything cron can do) or you can even disable "OnDemand" causing launchd to keep the process permanently running (if it quits or crashes, launchd will immediately restart it). You can even limit how much resources a process may use (as said before, Lingon shows all these settings in a nice UI interface).

此代理将每 1800 秒(每 30 分钟)运行一次 shell 脚本 /usr/local/bin/my-script.sh。您还可以在特定日期/时间运行任务(基本上 launchd 可以执行 cron 可以执行的所有操作),或者您甚至可以禁用“OnDemand”,从而使 launchd 保持进程永久运行(如果它退出或崩溃,launchd 将立即重新启动它) . 你甚至可以限制一个进程可以使用多少资源(如前所述,Lingon 在一个漂亮的 UI 界面中显示了所有这些设置)。

Update:Even though OnDemandis still supported, it is deprecated. The new setting is named KeepAlive, which makes much more sense. It can have a boolean value, in which case it is the exact opposite of OnDemand(setting it to falsebehaves as if OnDemandis trueand the other way round). The great new feature is, that it can also have a dictionary value instead of a boolean one. If it has a dictionary value, you have a couple of extra options that give you more fine grain control under which circumstances the task shall be kept alive. E.g. it is only kept alive as long as the program terminated with an exit code of zero, only as long as a certain file/directory on disk exists, only if another task is also alive, or only if the network is currently up.

更新:尽管OnDemand仍受支持,但已弃用。新设置名为KeepAlive,这更有意义。它可以有一个布尔值,在这种情况下,它与OnDemand(将其设置false为好像OnDemandtrue,反之亦然)正好相反。一个很棒的新功能是,它也可以有一个字典值而不是一个布尔值。如果它有一个字典值,你有几个额外的选项可以让你更精细地控制任务在哪种情况下应该保持活动状态。例如,它仅在程序以零退出代码终止时才保持活动状态,仅当磁盘上存在某个文件/目录时,仅当另一个任务也处于活动状态时,或者仅当网络当前处于启动状态时才保持活动状态。

Also you can manually enable/disable tasks via command line:

您也可以通过命令行手动启用/禁用任务:

launchctl <command> <parameter>

command can be load or unload, to load a plist or unload it again, in which case parameter is the path to the file. Or command can be start or stop, to just start or stop such a task, in which case parameter is the label (com.example.my-fancy-task). Other commands and options exist as well.

command 可以是 load 或 unload,加载一个 plist 或再次卸载它,在这种情况下,参数是文件的路径。或者命令可以是开始或停止,只是开始或停止这样的任务,在这种情况下,参数是标签(com.example.my-fancy-task)。其他命令和选项也存在。

See Apple's documentation of the plist formatand of the launchctlcommand line tool(note that you can select the OS X version on top, since the format/options do vary between different OS X releases)

请参阅 Apple 的plist 格式launchctl命令行工具的文档(请注意,您可以在顶部选择 OS X 版本,因为不同 OS X 版本之间的格式/选项确实有所不同)

回答by Kosmotaur

you could use the very convenient plist generator: http://launched.zerowidth.com/(no need to buy anything…)

您可以使用非常方便的 plist 生成器:http: //launched.zerowidth.com/(无需购买任何东西...)

it will give you a shell one-liner to register a new scheduled job with the already recommended launchd

它会给你一个 shell one-liner 来用已经推荐的launchd注册一个新的预定作业

回答by Bruno De Fraine

On MacOSX, you have at least the following options:

在 MacOSX 上,您至少有以下选项:

  • 带有“运行脚本”操作的重复 iCal 警报
  • 启动
  • 的cron(LINK1LINK2

From personal experience, cron is the most reliable. When I tested, launchd had a number of bugs and quirks. iCal alarms only run when you are logged in (but that might be something you prefer).

从个人经验来看,cron是最可靠的。当我测试时,launchd 有许多错误和怪癖。iCal 警报仅在您登录时运行(但这可能是您更喜欢的)。

回答by Jay

As Mecki pointed out, launchd would be the way to go with this. There's a GUI interface for launchd called Lingonthat you might want to check out, as opposed to editing the launchd files by hand:

正如 Mecki 指出的那样,launchd 将是解决此问题的方法。launchd 有一个名为Lingon的 GUI 界面,您可能想要查看,而不是手动编辑 launchd 文件:

Lingon is a graphical user interface for creating an editing launchd configuration files for Mac OS X Leopard 10.5.

[snip...]

Editing a configuration file is easier than ever in this version and it has two different modes. Basic Mode which has the most common settings readily available in a very simple interface and Expert Mode where you can add all settings either directly in the text or insert them through a menu.

Lingon 是一个图形用户界面,用于为 Mac OS X Leopard 10.5 创建编辑启动配置文件。

[剪辑...]

在这个版本中编辑配置文件比以往任何时候都容易,它有两种不同的模式。基本模式具有非常简单的界面和专家模式中最常用的设置,您可以在其中直接在文本中添加所有设置或通过菜单插入它们。

回答by Jlearner

MAC OS has an AutomatorTool which is same as that of Task Schedulerin windows. And using Automator you can schedule tasks on daily basis and link the task with recurring calendar event to run scripts on specified time daily. refer link to run scripts on daily basis in Mac OS

MAC OS 有一个AutomatorTool,它与windows中的Task Scheduler相同。使用 Automator,您可以每天安排任务,并将任务与重复日历事件联系起来,以便每天在指定时间运行脚本。请参阅链接以在 Mac OS 中每天运行脚本

回答by Mike Heinz

For apple scripts, I set up a special iCal calendar and use alarms to run them periodically. For command line tools, I use launchd.

对于苹果脚本,我设置了一个特殊的 iCal 日历并使用闹钟定期运行它们。对于命令行工具,我使用launchd。

回答by Mike Heinz

FYI: while i do so miss it's siplicity, cron is a thing of the past on OS X. It was watchdog on panther. Since Tiger it has been launchd. So if you are running Leopard cron is not an option.

仅供参考:虽然我很想念它的简洁性,但 cron 在 OS X 上已成为过去。它是 panther 上的看门狗。自Tiger推出以来。因此,如果您正在运行 Leopard cron,则不是一种选择。

回答by UnchartedWorks

You can use cron to schedule tasks.

您可以使用 cron 来安排任务。

crontab -e

A job is specified in the following format.

作业按以下格式指定。

* * * * *  command to execute
│ │ │ │ │
│ │ │ │ └─── day of week (0 - 6) (0 to 6 are Sunday to Saturday, or use names; 7 is Sunday, the same as 0)
│ │ │ └──────── month (1 - 12)
│ │ └───────────── day of month (1 - 31)
│ └────────────────── hour (0 - 23)
└─────────────────────── min (0 - 59)

Example:

例子:

0 12 * * *  cd ~/backupfolder && ./backup.sh

Once you installed your cron tasks, you can use crontab -l to list your tasks.

安装 cron 任务后,您可以使用 crontab -l 列出您的任务。

crontab -l

If you want to know more about cron schedule expressions, you can access

如果您想了解更多有关 cron 调度表达式的信息,可以访问

https://crontab.guruhttps://ole.michelsen.dk/blog/schedule-jobs-with-crontab-on-mac-osx.html

https://crontab.guru https://ole.michelsen.dk/blog/schedule-jobs-with-crontab-on-mac-osx.html