How to terminate the execution of a process after some time in Linux

Suppose that you have to execute a Java program which is fairly unstable and sometimes hangs on and never terminates. Is there a simple way to make it terminate (actually by killing the process) after some time? Yes, of course. There is always a way for such things. Ways for everything do not exist though.

So, let's say you have a program.jar to execute but you want to kill its process after 5 minutes in case it does not terminate. A very easy way to do this is the following:

#!/bin/bash

# here you set the time you want to wait before killing the process
time=5m

# then you run your program in the background
java -jar program.jar &

# you are waiting for the time you have set
sleep $time

# some printing - for fun
termination="\nTerminating the process...!!\n"
echo -e $termination

# and now you are about to kill it
kill %1

You can create a script.sh file, just copy paste the code above, and then run the script.sh file (by using the command > sh script.sh).

Hints on linux cron jobs - A quick tutorial

Hint 1: Keep in mind that cron does not know where your home directory is OR does not see your directory structure. Be careful and specify the full path of the things you call (like /usr/java/bin/java etc.). This is not enough; in several occasions you have to add an extra line to your crontab file in order to define your HOME path. It might be something like that:

HOME=/
You have to write this inside the crontab file.


Hint 2
: How do I edit my cron jobs? You have to open a file called the "crontab" and simply edit it. To do that just type:

>> crontab -e
Beautiful vi editor will open; now you can edit your cron jobs.


Hint 3
: I hate vi. How do I open the crontab with an other editor?
You have to type three commands this time:

>> EDITOR=gedit (I pick gedit - you may pick another editor)
>> export EDITOR
>> alias editor=$EDITOR
Now run crontab -e again and the beautiful gedit will open (civilisation!).


Hint 4
: Hmm, what else should I write inside the crontab file? What about the actual syntax of the cron jobs? OK, it is nothing special. You just have to type a command to be executed. Right BEFORE the command you have to specify WHEN do you want to execute this command (or how often). You will use 5 space separated text fields for that. This is an example of a line in a crontab file:

* * * * * /usr/java1.6_02/bin/java -jar /home/programs/tetris/dist/tetris.jar
This creates a cron job that will open a tetris java based game. The 5 stars mean that this thing will be executed once per minute (and after a while your computer will have a problem because this .jar is not a very light or smart application). Actually the first star controls minutes, the second hours, the third days, the fourth months and the fifth years. It is really simple. Is it? How do I set a cron job to run every two minutes? This is how:
*/2 * * * * <your_command>
You just have to type a slash 2 right next to the first star!

 

How do I set a cron job to run every day at 21.00?

0 21 * * * <your_command>
That's it... -:)


Hint 5
: How do I avoid receiving this huge email with the cron job's output?

Implicit declaration of function abs

You are a beginner in C programming language (maybe 1st year student in a computer science department) and you want to meet a deadline for a programming assignment. The program specification is simple (because it is still the beginning) but there is something annoying happenning with your source code.

The course instructor has forced you to compile your C programs with all the appropriate flags enabled, e.g.

>> gcc program_name.c -ansi -pedantic -Wall -o program_name

Your program includes mathematical functions and as a result you have included math.h library and you have added -lm flag during compilation time:

>> gcc program_name.c -ansi -pedantic -Wall -lm -o program_name

Your final program should work (perfectly!) and after compilation NO warnings should appear. Otherwise, you lose points on your final mark! :-)

You have followed all the instructions, your program is working(!) BUT you still get an annoying warning, like:

implicit declaration of function abs

You try again and again, you 'google' this warning but there is no RESULT. Usually, the compiler is absolutely right and points to the right direction (in simple programs of course). So, there is an implicit declation of the 'abs' function (which returns the absolute value of a number). Something is missing. What? The following line (in most of the cases):

#include <stdlib.h>

You should include stdlib.h library as well. Don't forget that! That's it ... it should have helped you! -:)

How to clear Apache Cayenne's cache?

In this post we refer to some simple ways - tricks in order to clear Apache Cayenne's cache. Clearing the cache is essential especially when huge datasets are extracted continuously from the database (and passed into objects).

A nice and easy solution for this is to create a new DataContext before executing queries that will fetch huge amounts of data. You just have to create a new object each time (before the query):

DataContext context = new DataContext.createDataContext();

and then use this for your query:

List queryRows = context.performQuery(selectQuery);

Another way, which is not always very effective but it can be used together with the previous one is to directly clear the data rows from the object store cache.

context.getObjectStore().getDataRowCache().clear();

In heavy duty applications you should always adjust the memory for the java heap using the runtime arguments -Xms128m (mininum memory size set to 128Mb) and -Xmx512m (maximum memory size set to 512 Mb). The values (128 and 512) are just an example (you should test your code and find out the right numbers for these values).

How to sort the values of a HashMap in Java and keep the duplicate entries

This is another way to sort a HashMap. This way is more useful as it sorts the HashMap and keeps the duplicate values as well.

public LinkedHashMap sortHashMapByValuesD(HashMap passedMap) {
    List mapKeys = new ArrayList(passedMap.keySet());
    List mapValues = new ArrayList(passedMap.values());
    Collections.sort(mapValues);
    Collections.sort(mapKeys);
        
    LinkedHashMap sortedMap = 
        new LinkedHashMap();
    
    Iterator valueIt = mapValues.iterator();
    while (valueIt.hasNext()) {
        Object val = valueIt.next();
        Iterator keyIt = mapKeys.iterator();
        
        while (keyIt.hasNext()) {
            Object key = keyIt.next();
            String comp1 = passedMap.get(key).toString();
            String comp2 = val.toString();
            
            if (comp1.equals(comp2)){
                passedMap.remove(key);
                mapKeys.remove(key);
                sortedMap.put((String)key, (Double)val);
                break;
            }

        }

    }
    return sortedMap;
}
Syndicate content