linux操作系统下crontab命令及使用案例介绍

韵味老鸟 2024-09-16 04:54:46

linux 操作系统下crontab命令及使用案例介绍

Linux 操作系统下的 crontab 命令用于设置周期性执行的任务

crontab 命令概述基本语法bashcrontab [-u user] file crontab [-u user] [-l | -r | -e] [-i] [-s]主要功能创建、编辑和管理用户的计划任务(cron job)。每个用户都可以有自己的 crontab 文件。cron 守护进程会定期检查 crontab 文件并执行相应的任务。常用选项-u user: 指定要编辑的用户的 crontab 文件。-l: 列出当前用户的 crontab 内容。-r: 删除当前用户的 crontab 文件。-e: 编辑当前用户的 crontab 文件。-i: 在删除 crontab 时给出提示。

crontab 文件格式

每个 crontab 文件的每一行都包含以下字段:

textminute hour day-of-month month day-of-week commandminute: 0-59hour: 0-23day-of-month: 1-31month: 1-12 或 Jan-Decday-of-week: 0-6 (0 表示周日) 或 Sun-Satcommand: 要执行的命令或脚本

命令:

root@meng:~# which crontab

/usr/bin/crontab

root@meng:~# crontab --help

crontab: invalid option -- '-'

crontab: usage error: unrecognized option

usage: crontab [-u user] file

crontab [ -u user ] [ -i ] { -e | -l | -r }

(default operation is replace, per 1003.2)

-e (edit user's crontab)

-l (list user's crontab)

-r (delete user's crontab)

-i (prompt before deleting user's crontab)

root@meng:~# crontab

^Z^Croot@meng:~#

命令案例:

修改crontab默认编辑器

root@meng:~# select-editor

Select an editor. To change later, run 'select-editor'.

1. /bin/nano <---- easiest

2. /usr/bin/vim.basic

3. /usr/bin/vim.tiny

4. /bin/ed

Choose 1-4 [1]: 2

root@meng:~#

命令案例;

root@meng:~# ls

f1.txt.bz2 f2.txt.bz2 m1.txt m1.txt.bak m2.txt meng meng.cpio meng.sh meng.txt meng.txt.bz2 rec00001f1.txt s1.txt s2.txt snap tmp

root@meng:~# pwd

/root

root@meng:~# cat meng

cat: meng: Is a directory

root@meng:~# cat meng.sh

#!/bin/bash

echo "meng"

root@meng:~# crontab -e

no crontab for root - using an empty one

crontab: installing new crontab

root@meng:~# crontab -l

# Edit this file to introduce tasks to be run by cron.

#

# Each task to run has to be defined through a single line

# indicating with different fields when the task will be run

# and what command to run for the task

#

# To define the time you can provide concrete values for

# minute (m), hour (h), day of month (dom), month (mon),

# and day of week (dow) or use '*' in these fields (for 'any').

#

# Notice that tasks will be started based on the cron's system

# daemon's notion of time and timezones.

#

# Output of the crontab jobs (including errors) is sent through

# email to the user the crontab file belongs to (unless redirected).

#

# For example, you can run a backup of all your user accounts

# at 5 a.m every week with:

# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/

#

# For more information see the manual pages of crontab(5) and cron(8)

#

# m h dom mon dow command

3 * * * * cd /root/meng; /bin/bash meng.sh

root@meng:~#

0 阅读:3