Linux CronJob - Yash-777/LearnJava GitHub Wiki

Bash Shell Reference (manual)

CronJob file to Output to file: Job to log

*/1 * * * * /home/ranveer/vimbackup.sh >> /home/ranveer/vimbackup.log 2>&1
Providing Full Permission:

[root@Yash@777 cornjob_folder]# chmod 777 NeonScan.sh
[root@Yash@777 cornjob_folder]# chmod 777 scanlogprogram.log

Making SH file as Executable, executing file:

[root@Yash@777 cornjob_folder]# chmod -x job.sh
[root@Yash@777 cornjob_folder]# ./job.sh

Cron Tab file Job:

[root@Yash@777 cornjob_folder]# crontab -l
SHELL=/bin/bash
*/5 * * * * /cornjob_folder/job.sh

Crond Service status, start, restart, stop options:

[root@Yash@777 cornjob_folder]# service crond restart
Redirecting to /bin/systemctl restart crond.service
[root@Yash@777 cornjob_folder]# service crond status
Redirecting to /bin/systemctl status crond.service

[root@Yash@777]# cd ..
[root@Yash@777]# cd cornjob_folder/

WinSCP is a popular SFTP client and FTP client for Microsoft Windows! Copy file between a local computer and remote servers using FTP, FTPS, SCP, SFTP, WebDAV or S3 file transfer protocols.

Switch to Root user: sudo su -

PuTTY is an SSH and telnet client, developed originally by Simon Tatham for the Windows platform. PuTTY is open source software that is available with source code and is developed and supported by a group of volunteers.

my-script.sh

#!/bin/sh
# This is a comment!
echo Hello World	# This is a comment, too!

[Make file contains only provided data '&>' or '>' ~]# cat /cron/job.sh
echo "hai" &> /cron/log.txt

Multiple line to file:

  • String literal containing newlines.

    echo 'First line. https://unix.stackexchange.com/a/159708
    Second line.
    Third line.' > /cron/log.txt
  • EOM - https://stackoverflow.com/a/18226936/5081877

    [File Creation with data, Use Ctrl+D to end ~]# cat >/cron/job2.sh
    #!/bin/sh
    
    FILE="/path/to/file"
    
    /bin/cat <<EOM >$FILE
    text1 append it to file
    text2 # This comment will be inside of the file.
    The keyword EOM can be any text, but it must start the line and be alone.
     EOM # This will be also inside of the file, see the space in front of EOM.
    EOM # No comments and spaces around here, or it will not work.
    text4
    EOM
  • > file.txt - Overwrite the text in the file

  • >> file.txt - Append with text in the file

Shell script to run jarfile and write its output to log file:

JAVA_BIN="/java/jdk1.8.0_151/bin/java"
JarFile="/tomcat/Customfolder"
Logs_to_Place="/tomcat/apache-tomcat-8.5.37/logs"
# Appending the above path to System Path:
PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:$JAVA_BIN:$JarFile:$Logs_to_Place:$PATH"

if [ -e $JarFile ]; 
then
	cd $JarFile
    $JAVA_BIN -jar $JarFile/log-scanner.jar &> scanlogprogram.log
     cp -rf scanlogprogram.log $Logs_to_Place/
    cp -rf *.csv $Logs_to_Place/
else
	echo "file does not exist : $JarFile"
fi
echo "Script ran successfully review: $Logs_to_Place/scanlogprogram.log for details"
#!/bin/bash # https://www.cyberciti.biz/faq/hello-world-bash-shell-script/
# Define bash shell variable called var 
# Avoid spaces around the assignment operator (=)
var="Hello World"

echo "$var" # print it 
printf "%s\n" "$var" # Another way of printing it

Vim is a highly configurable text editor for efficiently creating and changing any kind of text. It is included as "vi" with most UNIX systems and with Apple OS X.

[root@Yash ~]# vi /CrontabJobs/log.txt   <!-- New file creates and opens -->

To view file use cat:

[File View ~]# cat /cron/log.txt
[List out folder files ~]# ls -l /cron
total 12
-rwxrwxrwx. 1 root root 339 Oct 17 16:04 job2.sh
-rw-r--r--. 1 root root  33 Oct 17 14:16 job.sh
-rwxrwxrwx. 1 root root 275 Oct 17 14:40 log.txt

UNIX vi commands sample links

tipsandtricks-hq.com cs.colostate.edu Understanding and Using File Permissions

  • Changing File Permissions: /bin/bash: /cron/job.sh: Permission denied « Try to provide fill permission to file using chmod 777 /cron/job.sh
  • Press ESC to get control of file
  • Use i to make file in -- INSERT -- mode
  • Make the script executable with command chmod +x /cron/job.
  • :wq to save and close the file with changes
  • :q to close file file with out any changes.

Cron-Job, crontab

Usage:

 crontab [options] file
 crontab [options]
 crontab -n [hostname]

Options:
 -u <user>  define user
 -e         edit user's crontab
 -l         list user's crontab
 -r         delete user's crontab
 -i         prompt before deleting
 -n <host>  set host in cluster to run users' crontabs
 -c         get host in cluster to run users' crontabs
 -s         selinux context
 -x <mask>  enable debugging

User crontabs: The * means all the possible unit

# Example of job definition:
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7)
# |  |  |  |  |
# *  *  *  *  *   command to be executed

The default crontab file consist of:

[root@Yash ~]# crontab -l
# Below code in single line
* * * * * [ -f /etc/krb5.keytab ] && [ \( ! -f /etc/opt/omi/creds/omi.keytab \) 
-o \( /etc/krb5.keytab -nt /etc/opt/omi/creds/omi.keytab \) ] 
&& /opt/omi/bin/support/ktstrip /etc/krb5.keytab /etc/opt/omi/creds/omi.keytab >/dev/null 2>&1 || true

Installing new crontab:

[Cron file edit ~]# crontab -e
SHELL=/bin/bash
*/1 * * * * /cron/job.sh


[root@Yash ~]# cat /cron/job.sh
#!/bin/sh

currentDate=`date`
echo $currentDate >> /cron/log.txt

Services Start and stop:

[root@Yash ~]# service crond restart
Redirecting to /bin/systemctl restart crond.service

[root@Yash ~]# service crond status
Redirecting to /bin/systemctl status crond.service

[root@Yash ~]# service crond stop
Redirecting to /bin/systemctl stop crond.service

Window using Java

<!-- Quartz API -->
<dependency>
	<groupId>org.quartz-scheduler</groupId>
	<artifactId>quartz</artifactId>
	<version>2.1.5</version>
</dependency>
public class Quartz_2_1_5 {
    // https://stackoverflow.com/questions/22163662/how-to-create-a-java-cron-job
    
    // http://www.quartz-scheduler.org/documentation/quartz-2.3.0/tutorials/crontrigger.html
    // https://stackoverflow.com/questions/40521416/how-do-you-execute-cron-job-every-5-minutes
    public static void main(String[] args) throws SchedulerException, IOException {
        /*Scheduler scheduler = new StdSchedulerFactory().getScheduler();
        JobDetail job1 = JobBuilder.newJob(Quartz_JOB.class)
                        .withIdentity("New Job ID1", "Group1")
                        .build();
        
        Trigger trigger1 = TriggerBuilder
                .newTrigger()
                .withIdentity("New Trigger ID", "Group1")
                .forJob("New Job ID1", "Group1")
                .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                .withIntervalInSeconds(5).repeatForever())
                //.withSchedule(CronScheduleBuilder.cronSchedule("0/5 * * * * ?"))
                .build();
        
        System.out.println("Scheduler Started ");
        
        scheduler.scheduleJob(job1, trigger1);
        scheduler.start();*/
        
        Timer t = new Timer();
        MyTask mTask = new MyTask();
        // This task is scheduled to run every 10 seconds
        
        t.scheduleAtFixedRate(mTask, 0, 10000);
    }
}

class MyTask extends TimerTask{

    public MyTask(){
        //Some stuffs
    }

    @Override public void run() {
        System.out.println("Hi see you after 10 seconds");
    }
}

public class Quartz_JOB implements Job {
    
    public static Integer size;
    
    public void execute(JobExecutionContext context) throws JobExecutionException {
        Date time = context.getFireTime();
        Date next_trigger_time =context.getNextFireTime();
        System.out.println("### Current Trigget Time : "+time+"\n### Next Trigger Time : "+next_trigger_time);
        
        JobKey job_key = context.getJobDetail().getKey();
        System.out.println("Instance " + job_key);
    }
}
⚠️ **GitHub.com Fallback** ⚠️