Code in the following timeout example derives a Context and passes it into the sql.DB QueryContext method.

func QueryWithTimeout(ctx context.Context) {
    // Create a Context with a timeout.
    queryCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
    defer cancel()

    // Pass the timeout Context with a query.
    rows, err := db.QueryContext(queryCtx, "SELECT * FROM album")
    if err != nil {
        log.Fatal(err)
    }
    defer rows.Close()

    // Handle returned rows.
}
Code in the following timeout example derives a Context and passes it into the sql.DB QueryContext method.

func QueryWithTimeout(ctx context.Context) {
    // Create a Context with a timeout.
    queryCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
    defer cancel()

    // Pass the timeout Context with a query.
    rows, err := db.QueryContext(queryCtx, "SELECT * FROM album")
    if err != nil {
        log.Fatal(err)
    }
    defer rows.Close()

    // Handle returned rows.
}
You haven’t defined the PathSeparator yet, so do that now in another file. Save and quit main.go, open your favorite editor, and create a new file named path.go:

nano path.go
Next, create a new file in your text editor of choice named main.go. For this tutorial, we will use Nano:

nano main.go
This example uses Tx methods that take a context.Context argument. This makes it possible for the function’s execution – including database operations – to be canceled if it runs too long or the client connection closes. For more, see Canceling in-progress operations.

// CreateOrder creates an order for an album and returns the new order ID.
func CreateOrder(ctx context.Context, albumID, quantity, custID int) (orderID int64, err error) {

    // Create a helper function for preparing failure results.
    fail := func(err error) (int64, error) {
        return fmt.Errorf("CreateOrder: %v", err)
    }

    // Get a Tx for making transaction requests.
    tx, err := db.BeginTx(ctx, nil)
    if err != nil {
        return fail(err)
    }
    // Defer a rollback in case anything fails.
    defer tx.Rollback()

    // Confirm that album inventory is enough for the order.
    var enough bool
    if err = tx.QueryRowContext(ctx, "SELECT (quantity >= ?) from album where id = ?",
        quantity, albumID).Scan(&enough); err != nil {
        if err == sql.ErrNoRows {
            return fail(fmt.Errorf("no such album"))
        }
        return fail(err)
    }
    if !enough {
        return fail(fmt.Errorf("not enough inventory"))
    }

    // Update the album inventory to remove the quantity in the order.
    _, err = tx.ExecContext(ctx, "UPDATE album SET quantity = quantity - ? WHERE id = ?",
        quantity, albumID)
    if err != nil {
        return fail(err)
    }

    // Create a new row in the album_order table.
    result, err := tx.ExecContext(ctx, "INSERT INTO album_order (album_id, cust_id, quantity, date) VALUES (?, ?, ?, ?)",
        albumID, custID, quantity, time.Now())
    if err != nil {
        return fail(err)
    }
    // Get the ID of the order item just created.
    orderID, err := result.LastInsertId()
    if err != nil {
        return fail(err)
    }

    // Commit the transaction.
    if err = tx.Commit(); err != nil {
        return fail(err)
    }

    // Return the order ID.
    return orderID, nil
}

How use future and cancel task after timeout:


import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class Test {
    public static void main(String[] args) throws Exception {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Task t = new Task();
        Future<String> future = executor.submit(t);

        try {
            System.out.println("Started..");
            System.out.println(future.get(5, TimeUnit.SECONDS)); // throws
                                                                    // TimeoutException
            System.out.println("Finished!");
        } catch (TimeoutException e) {
            future.cancel(true);
            System.out.println("Terminated!");
        }
    }
}

class Task implements Callable<String> {
    @Override
    public String call() throws Exception {
        for (int i = 0; i < 1000; i++) {
            Thread.sleep(1000);
            System.out.println("task running!");
        }
        return "Ready!";
    }
}

You can use a ScheduledExecutorService for this. First you would submit it only once to begin immediately and retain the future that is created. After that you can submit a new task that would cancel the retained future after some period of time.


 ScheduledExecutorService executor = Executors.newScheduledThreadPool(2); 
 final Future handler = executor.submit(new Callable(){ ... });
 executor.schedule(new Runnable(){
     public void run(){
         handler.cancel();
     }      
 }, 10000, TimeUnit.MILLISECONDS);

First of all, with the code you posted you won't see the FacesMessage before the redirect, you'll see it after the redirect. But also, in order to make that happen you'll need to add a filter, because messages are lost when you redirect. This is the code for the filter you need (don't forget to declare it in web.xml):


public class MultiPageMessagesSupport implements PhaseListener {

private static final long serialVersionUID = 1250469273857785274L;
private static final String sessionToken = "MULTI_PAGE_MESSAGES_SUPPORT";

@Override
public PhaseId getPhaseId() {
    return PhaseId.ANY_PHASE;
}

/*
 * Check to see if we are "naturally" in the RENDER_RESPONSE phase. If we
 * have arrived here and the response is already complete, then the page is
 * not going to show up: don't display messages yet.
 */
@Override
public void beforePhase(final PhaseEvent event) {
    FacesContext facesContext = event.getFacesContext();
    int msg = this.saveMessages(facesContext);

    if (PhaseId.RENDER_RESPONSE.equals(event.getPhaseId())) {
        if (!facesContext.getResponseComplete()) {
            this.restoreMessages(facesContext);
        }
    }
}

/*
 * Save messages into the session after every phase.
 */
@Override
public void afterPhase(final PhaseEvent event) {
    if (event.getPhaseId() == PhaseId.APPLY_REQUEST_VALUES ||
            event.getPhaseId() == PhaseId.PROCESS_VALIDATIONS ||
            event.getPhaseId() == PhaseId.INVOKE_APPLICATION) {
        FacesContext facesContext = event.getFacesContext();
        int msg = this.saveMessages(facesContext);
    }
}

@SuppressWarnings("unchecked")
private int saveMessages(final FacesContext facesContext) {
    List<FacesMessage> messages = new ArrayList<FacesMessage>();
    for (Iterator<FacesMessage> iter = facesContext.getMessages(null); iter.hasNext();) {
        messages.add(iter.next());
        iter.remove();
    }

    if (messages.isEmpty()) {
        return 0;
    }

    Map<String, Object> sessionMap = facesContext.getExternalContext().getSessionMap();
    List<FacesMessage> existingMessages = (List<FacesMessage>) sessionMap.get(sessionToken);
    if (existingMessages != null) {
        existingMessages.addAll(messages);
    } else {
        sessionMap.put(sessionToken, messages);
    }
    return messages.size();
}

@SuppressWarnings("unchecked")
private int restoreMessages(final FacesContext facesContext) {
    Map<String, Object> sessionMap = facesContext.getExternalContext().getSessionMap();
    List<FacesMessage> messages = (List<FacesMessage>) sessionMap.remove(sessionToken);

    if (messages == null) {
        return 0;
    }

    int restoredCount = messages.size();
    for (Object element : messages) {
        facesContext.addMessage(null, (FacesMessage) element);
    }
    return restoredCount;
}
}

You can use Java provided built in Future where it provides the facility for timeout. See below the small code snippet.


ExecutorService ex = Executors.newSingleThreadExecutor();
    Future<?> future = ex.submit(new Runnable() {
        public void run() {
            try {
                //Do some long running operations
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Completed operation");
        }
    });
    Object someObject = future.get(10, TimeUnit.SECONDS);

If you're alright with being notified when the operation doesn't complete within a certain time frame, but allowing the original operation to complete, then you can create an extension method, like so:


public static async Task<T> WithWaitCancellation<T>( 
    this Task<T> task, CancellationToken cancellationToken) 
{
    // The tasck completion source. 
    var tcs = new TaskCompletionSource<bool>(); 

    // Register with the cancellation token.
    using(cancellationToken.Register( s => ((TaskCompletionSource<bool>)s).TrySetResult(true), tcs) ) 
    {
        // If the task waited on is the cancellation token...
        if (task != await Task.WhenAny(task, tcs.Task)) 
            throw new OperationCanceledException(cancellationToken); 
    }

    // Wait for one or the other to complete.
    return await task; 
}

Recommend

Go Executing SQL statements that don't return data

Go Executing transactions Example

Go Querying for data Handling multiple result sets

Go Querying for data Handling nullable column values

Go Querying for data Querying for multiple rows

Go Querying for data Querying for a single row

Go Avoiding SQL injection risk

Go Using prepared statements How you use prepared statements

Go Opening a database handle Freeing resources

Go Opening a database handle Storing database credentials

Go Opening a database handle Confirming a connection

Go Opening a database handle Opening a database handle Opening with a Connector

Go Opening a database handle Opening a database handle Opening with a connection string

Go Opening a database handle Locating and importing a database driver

Go Call your code from another module

Go Compile and install the application

Go Return greetings for multiple people

Tutorial: Get started with Go Call code in an external package

Tutorial: Get started with Go Write some code

Go Tutorial: Getting started with fuzzing Completed code

Go Tutorial: Getting started with fuzzing Fix the double reverse error Fix the error Run the code

Go Tutorial: Getting started with fuzzing Fix the double reverse error Fix the error Write the code

Go Tutorial: Getting started with fuzzing Fix the double reverse error Diagnose the error Run the code

Go Tutorial: Getting started with fuzzing Fix the double reverse error Diagnose the error Write the code

Go Tutorial: Getting started with fuzzing Fix the invalid string error Fix the error Run the code

Go Tutorial: Getting started with fuzzing Fix the invalid string error Fix the error Write the code

Go Tutorial: Getting started with fuzzing Fix the invalid string error Diagnose the error Run the code

Go Tutorial: Getting started with fuzzing Fix the invalid string error Diagnose the error Write the code

Go Tutorial: Getting started with fuzzing Fix the invalid string error Diagnose the error

Go Tutorial: Getting started with fuzzing Add a fuzz test Run the code

Go Tutorial: Getting started with fuzzing Add a fuzz test Write the code

Go Tutorial: Getting started with fuzzing Add a unit test Run the code

Go Tutorial: Getting started with fuzzing Add a unit test Write the code

Go Tutorial: Getting started with fuzzing Add code to test Run the code

Go Tutorial: Getting started with fuzzing Add code to test Write the code

Go Tutorial: Getting started with fuzzing Create a folder for your code

Tutorial: Create a Go module Start a module that others can use

Go Add a test

Go Return and handle an error

Go Return a random greeting

Go Tutorial: Getting started with multi-module workspaces Download and modify the golang.org/x/example module Future step

Go Tutorial: Getting started with multi-module workspaces Download and modify the golang.org/x/example module Run the code in the workspace

Go Tutorial: Getting started with multi-module workspaces Download and modify the golang.org/x/example module