如何在Java中的特定给定超时(5秒)内停止方法执行?

时间:2018-05-17 11:48:40

标签: java

可以终止方法执行,也可以指定方法超时。实际上我有一个要求,如果我给出应该在给定特定时间内完成的方法超时,如果没有,则终止方法执行。

2 个答案:

答案 0 :(得分:1)

这可以计算从执行开始的时间。

Option Explicit
 Sub Match_ProjCode()
 Dim CSAT_Comments As Workbook
 Dim comment As Worksheet
 Dim matchcomment As Worksheet
 Dim comment_string As String 'To store the comment
 Dim Column As Integer
 Dim Row As Integer
 Dim match_Row As Integer
 Dim comments_Column_Name As String '
 Dim Comments_Column_Value As String 
 Dim Comments_ProjCode As String 'To store the project code
 Dim RangeObj As Range

Set CSAT_Comments = ActiveWorkbook
Set comment = CSAT_Comments.Worksheets("Qualitative Analysis_2018 Cycle") ' 
Set matchcomment = CSAT_Comments.Worksheets("Consolidated Comments") '

Dim range1 As Range
Dim rng As Range
matchcomment.Range("A2").Select

Set range1 = matchcomment.Range(Selection, Selection.End(xlDown)) 



For Each rng In range1.SpecialCells(xlCellTypeVisible)

comment_string = rng.Value ' Comment text will be stored
match_Row = rng.Row 'comment row will be stored

With comment
.Activate
Columns("AK:BL").Select

      Set RangeObj = Selection.Find(What:=comment_string, After:=ActiveCell, LookIn:=xlFormulas, _
    LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
    MatchCase:=False, SearchFormat:=False) ' to search for the comment in the comment worksheet

    If Not RangeObj Is Nothing Then               

    .Range(RangeObj.Address).Select 'Select the cell of the searched value
    Column = ActiveCell.Column 'Get the column number of the searched value
    Row = ActiveCell.Row ' Get the row number of the searched value

    comments_Column_Name = Split(Cells(, Column).Address, "$")(1) ' Trim the column name from the cell address
    Comments_Column_Value = .Range("" & comments_Column_Name & 1) ' Get the comment heading
    Comments_ProjCode = .Range("A" & Row) 'Get the project code

             With matchcomment
             .Activate
             .Range("C" & match_Row) = Comments_Column_Value ' Paste the comment heading name in the match sheet
             .Range("D" & match_Row) = Comments_ProjCode 'Paste the project code in the match sheet
            End With
    Else
   End If

End With
Next rng
End Sub

修改

long startTime = System.currentTimeMillis()/1000;
int timeExec = 5;
while( ( System.currentTimeMillis() / 1000 ) - startTime < timeExec){
    //TODO
}

答案 1 :(得分:0)

我明白了,如何在给定时间内终止方法执行。

class TimerTask implements Runnable{
private FTPClient client;
public static FTPFile[] files;

public TimerTask(FTPClient client) {
    this.client=client;
    files=null;
    System.out.println("client is Connected: "+client.isConnected());
}
@Override
public void run() {
    PacketHandler tcph = new PacketHandler();
    files=tcph.getFiles(client); // custom get files method(-)
}
}

编写另一种想要使用它的方法。

public void myService(){    
final ExecutorService service = Executors.newSingleThreadExecutor();
        boolean timeoutFlag=true;
        FTPFile[] files=null;
        TimerTask st= new TimerTask(client);

        try {
            final Future<TimerTask> f =  (Future<TimerTask>) service.submit(st);
            f.get(6, TimeUnit.SECONDS) // give here the execution time in 6 seconds 
            System.out.println("count files:"+TimerTask.files.length);
            files=TimerTask.files;
        } catch (final TimeoutException e) {
            timeoutFlag=false;
            Print.logInfo("Timeout exception..");
            System.out.println("Timeout exception");
        } catch (final Exception e) {
            timeoutFlag=false;
            Print.logInfo("Timeout exception : "+e.getMessage());
            System.out.println("timeout exception "+e.getMessage() );
            throw new RuntimeException(e);
        } finally {
            service.shutdown();
        }
}