首先需要开启win10下的ubuntu子系统,如何开启参考文章Windows10 安装Ubuntu子系统
打开Windows Powershell,输入bash回车即可进入ubuntu子系统,输入cat /etc/issue回车即可查看当前Ubuntu版本号
Windows PowerShell
版权所有 (C) Microsoft Corporation。保留所有权利。
PS C:\Users\ming> bash
root@DESKTOP-8PR647D:/mnt/c/Users/ming# cat /etc/issue
Ubuntu 16.04.2 LTS \n \l
root@DESKTOP-8PR647D:/mnt/c/Users/ming#
默认的路径为win10对应的C:\Users\ming文件夹
在当前文件夹下创建一个名为task的文件夹,用于储存计划任务的文件
root@DESKTOP-8PR647D:/mnt/c/Users/ming# mkdir task
创建计划任务有两种方式,一种是使用crontab -e命令编辑计划任务表,另一种是用启动cron服务启动计划任务的文件
第一种方式crontab -e创建任务:
输入crontab -e创建任务表,进入task文件夹:
root@DESKTOP-8PR647D:/mnt/c/Users/ming# cd task/
root@DESKTOP-8PR647D:/mnt/c/Users/ming/task# crontab -e
编辑计划任务为* * * * * /bin/sh /mnt/c/Users/ming/task/hello.sh >> /mnt/c/Users/ming/task/hello.log,表示每分钟执行一次task目录下的hello.sh文件,并将结果储存到同文件夹下的hello.log文件中。
# 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
* * * * * /bin/sh /mnt/c/Users/ming/task/hello.sh >> /mnt/c/Users/ming/task/hello.log
~ ~ -- INSERT --
还需要创建hello.sh和一个空的hello.log文件,创建hello.sh文件:
root@DESKTOP-8PR647D:/mnt/c/Users/ming/task# vim hello.sh
内容为输出Hello World和对应的时间,
#!/bin/sh
echo $(date '+%Y-%m-%d %H:%M:%S');
echo "Hello World"
运行cron服务启动计划任务
root@DESKTOP-8PR647D:/mnt/c/Users/ming/task# service cron start
* Starting periodic command scheduler cron [ OK ]
root@DESKTOP-8PR647D:/mnt/c/Users/ming/task#
每隔一分钟,就会输入对应的信息到hello.log中:
第二种方式:文件创建计划任务
创建hello文件并编辑:
root@DESKTOP-8PR647D:/mnt/c/Users/ming/task# vim hello
写入任务:
* * * * * /bin/sh /mnt/c/Users/ming/task/hello.sh >> /mnt/c/Users/ming/task/hello.log
~ ~ ~ -- INSERT --
保存退出,执行:
root@DESKTOP-8PR647D:/mnt/c/Users/ming/task# crontab hello
同样会在hello.log输出对应的信息:
{
将hello.sh的顶部加上#!/bin/sh
在运行shell命令
root@DESKTOP-8PR647D:/mnt/c/Users/ming/task# sh /mnt/c/Users/ming/task/hello.sh >> /mnt/c/U
sers/ming/task/hello.log
root@DESKTOP-8PR647D:/mnt/c/Users/ming/task#
可以在hello.log打印一次结果,可用于检测hello.sh是否正确输出.
}